Two more test cases for DependencyInjectionSpecificationTests to test disposable singletons
See original GitHub issue.NET Core dependency injection is a “tracking” container, i.e. it tracks disposable objects and disposes them if the container is disposed or the scope is left.
When a disposable singleton is registered, the container only tracks the object if it is created by a factory, in order to dispose it if the container itself is disposed. If the singleton is added as an existing instance, the container does not track the object, and it does not dispose it. This behavior is correct since disposable singletons which are added as an existing instance are considered “externally owned”.
However, some 3rd party containers which implement the .NET Core abstractions behave differently here, e.g. Autofac.
I propose to file two additional test cases to check the behavior mentioned above:
using System;
using System.Collections.Generic;
using Xunit;
namespace Microsoft.Extensions.DependencyInjection.Specification
{
public abstract class DependencyInjectionSpecificationTests2 : DependencyInjectionSpecificationTests
{
[Fact]
public void SingletonServiceCreatedFromFactoryIsDisposedWhenContainerIsDisposed()
{
// Arrange
var collection = new TestServiceCollection();
collection.AddSingleton(_ => new TestDisposable());
var provider = this.CreateServiceProvider(collection);
// Act
var service = provider.GetService<TestDisposable>();
((IDisposable)provider).Dispose();
// Assert
Assert.True(service.IsDisposed);
}
[Fact]
public void SingletonServiceCreatedFromInstanceIsNotDisposedWhenContainerIsDisposed()
{
// Arrange
var collection = new TestServiceCollection();
collection.AddSingleton(new TestDisposable());
var provider = this.CreateServiceProvider(collection);
// Act
var service = provider.GetService<TestDisposable>();
((IDisposable)provider).Dispose();
// Assert
Assert.False(service.IsDisposed);
}
internal class TestDisposable : IDisposable
{
public bool IsDisposed { get; private set; }
public void Dispose()
{
this.IsDisposed = true;
}
}
internal class TestServiceCollection : List<ServiceDescriptor>, IServiceCollection
{
}
}
}
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
@peter-perot, I’ve just submitted a PR for this. If you’d rather submit one yourself, that’s OK too, and I can have mine deleted.
@tomakita Thank you for setting up a PR.