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
:
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:
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