ASP.NET Core Interview Question #71

How does ASP.NET Core dispose dependency-injected services?

Dependency Injection & Services Junior Beginner

Quick Interview Answer

The built-in DI container tracks disposable services that it creates and disposes them when the owning scope is disposed.

Detailed Explanation

The built-in DI container tracks disposable services that it creates and disposes them when the owning scope is disposed.

Scoped disposable services are normally disposed at the end of the request scope. Singleton disposable services are disposed when the application service provider shuts down. Transient disposable services resolved from a scope are also tracked by that scope.

A service instance created manually by application code is generally the responsibility of that code. Developers should avoid resolving large numbers of disposable transient services from the root provider because they can remain tracked until application shutdown.

Code Example

public sealed class FileProcessor : IDisposable
{
    public void Dispose()
    {
        // Release owned resources.
    }
}

builder.Services.AddScoped<FileProcessor>();