How to make ServiceProvider to call Dispose on objects created manually?
Solution 1:
I know this is old but maybe it will help to clarify a bit.
You can create object yourself and register using implementation factory. DI will take care of disposing object, as it is taking ownership of it by calling factory method.
It is described in msdn.
var instance = new MyDisposableObj();
var services = new ServiceCollection();
services.AddSingleton(x => instance);
var container = services.BuildServiceProvider();
container.Dispose();
You can verify this with simple unit test
[Fact]
public void ServiceProvider_SingletonObjectAddedAsFactory_IsDisposedWithContainer()
{
// Arrange
var sc = new ServiceCollection();
var fake = A.Fake<IDisposable>();
sc.AddSingleton(x => fake);
// Act
var sp = sc.BuildServiceProvider();
var recieved = sp.GetService<IDisposable>();
sp.Dispose();
// Assert
recieved.Should().NotBeNull();
A.CallTo(() => fake.Dispose()).MustHaveHappenedOnceExactly();
}