Services in .NET Core can be registered using the built-in dependency injection functionality with different lifetimes:
- Transient
- Scoped
- Singleton
Scoped services are created for a specific period of time linked to a scope. For example when using ASP.NET Core a scoped service lifetime is coupled to a client request.
An important feature of scoped services is that they are disposed when the scope is closed.
It is possible to create a scope yourself using the CreateScope
method on the IServiceProvider
:
public class Foo:IDisposable | |
{ | |
public void Dispose() | |
{ | |
Debug.WriteLine("Disposing..."); | |
} | |
} |
using System; | |
using System.Threading.Tasks; | |
using Microsoft.Extensions.DependencyInjection; | |
public class Program | |
{ | |
public static async Task Main() | |
{ | |
var provider = new ServiceCollection() | |
.AddScoped<Foo>() | |
.BuildServiceProvider(); | |
using (var scope = provider.CreateScope()) | |
{ | |
var foo = scope.ServiceProvider.GetRequiredService<Foo>(); | |
} | |
} | |
} |
If you run the example above youāll see that the Foo
instance is correctly disposed after leaving the scope.
So far, so good. But what about when your service implements the IAsyncDisposable
interface instead?
To support this scenario in a non-breaking way, a new CreateAsyncScope
method is introduced on the IServiceProvider
interface in .NET 6.
Here is an updated example using this feature:
class FooAsync : IAsyncDisposable | |
{ | |
public ValueTask DisposeAsync() | |
{ | |
Debug.WriteLine("Disposing..."); | |
return ValueTask.CompletedTask; | |
} | |
} |
sing System; | |
using System.Threading.Tasks; | |
using Microsoft.Extensions.DependencyInjection; | |
public class Program | |
{ | |
public static async Task Main() | |
{ | |
var provider = new ServiceCollection() | |
.AddScoped<Foo>() | |
.BuildServiceProvider(); | |
using (var scope = provider.CreateAsyncScope()) | |
{ | |
var foo = scope.ServiceProvider.GetRequiredService<Foo>(); | |
} | |
} | |
} |
Remark: ASP.NET Core was updated as well and implementations of IDisposable and IAsyncDisposable are properly disposed at the end of a request when registering them with a scoped service lifetime.
More information: Implement a DisposeAsync method | Microsoft Learn