After several years of using the same Dependency Injection (DI) framework like Autofac you may have a good understanding how your components, implementing the interface IDisposable, are going to be disposed.
With the nuget package Microsoft.Extensions.DependencyInjection the new .NET Core framework brings its own DI framework. It is not that powerful as the others but it is sufficient for simple constructor injection. Nonetheless, even if you don't need some advanced features you have to be aware of how the components are destroyed by this framework.
Let's look at a concrete example. Given are 2 classes, a
ParentClass and a
public class ParentClass : IDisposable
public ParentClass(ChildClass child)
public void Dispose()
public class ChildClass : IDisposable
public void Dispose()
At first we are using Autofac to resolve ParentClass:
var builder = new ContainerBuilder();
var container = builder.Build();
Console.WriteLine("== Autofac ==");
var parent = container.Resolve<ParentClass>();
With Autofac we are getting the following output:
== Autofac ==
And now we are using .NET Core DI:
var services = new ServiceCollection();
var provider = services.BuildServiceProvider();
Console.WriteLine("== .NET Core ==");
var parent = provider.GetRequiredService<ParentClass>();
The output we get is:
== .NET Core ==
Comparing the outputs we see that Autofac destroys the outer compontent (i.e.
ParentClass) first and then the inner component (i.e.
ChildClass). The .NET Core DI does not honor the dependency hierarchy and destroys the components in the same order they are created.
Most of the time the behavior of .NET Core DI is not a problem because the components just free internal resources and are done. But in some cases the outer component has to do something like to unregister from the inner component that may live on. If the inner component is/will not be disposed then all works fine; if not then we get
If you start a new project with .NET Core I suggest to stay with DI framework you are familiar with unless it is a sample application.
PS: Further information of how to switch from .NET Core DI to other frameworks in an ASP.NET Core application: Replacing the default services container and ASP.NET Core with Autofac