Why it matters
undisposed scopes can retain scoped and transient disposable services longer than expected, causing memory and handle leaks.
If you borrow a paintbrush and never wash it, it dries out and ruins the next project.
DI001
`IServiceScope` instances created with `CreateScope()` or `CreateAsyncScope()` that are never disposed.
Why it matters
undisposed scopes can retain scoped and transient disposable services longer than expected, causing memory and handle leaks.
If you borrow a paintbrush and never wash it, it dries out and ruins the next project.
Install
dotnet add package DependencyInjection.Lifetime.Analyzers --version 2.2.2
README problem example
public void Process()
{
var scope = _scopeFactory.CreateScope();
var svc = scope.ServiceProvider.GetRequiredService<IMyService>();
svc.Run();
}
README better pattern
public void Process()
{
using var scope = _scopeFactory.CreateScope();
var svc = scope.ServiceProvider.GetRequiredService<IMyService>();
svc.Run();
}
Repo sample extraction
Sample app warning case
public void Bad_ScopeNotDisposed()
{
// DI001: IServiceScope created by 'CreateScope' is not disposed
var scope = _scopeFactory.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<IScopedService>();
service.DoWork();
// Missing: scope.Dispose() or using statement
}
Sample app safe pattern
public void Good_UsingDeclaration()
{
using var scope = _scopeFactory.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<IScopedService>();
service.DoWork();
}
Related guides
More documentation