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, including scopes whose only disposal call is hidden behind a conditional branch, or behind a switch section, loop, or catch block that does not also contain the creation, or after a branch exit that can bypass shared cleanup. Create-and-dispose within the same loop iteration, switch section, or catch clause — the per-message worker shape — stays quiet, but a continue/break that skips the dispose, or a yield return/yield break that can strand the scope in a never-resumed iterator, still reports. DI001 recognizes predeclared nullable scope locals assigned conditionally when a later conditional-access, non-null-guarded, same-branch pre-exit, or finally disposal reliably closes ownership, and it treats directly returned scopes as caller-owned even through simple casts or conditional return arms. Reassignment leaks and loop-created scopes that need per-iteration disposal still report.
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 3.7.8
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
Nearby diagnostics
DI002
DI003