Why it matters
once the scope is disposed, that service may point to disposed state.
It is like taking an ice cube out of the freezer for later; by the time you need it, it has melted.
DI002
a service resolved from a scope that is returned or stored somewhere longer-lived, including services resolved through provider aliases, delegates that capture scoped services and then escape, scopes disposed later via `using (scope)`, and the same patterns inside constructors, accessors, local functions, lambdas, and anonymous methods.
Why it matters
once the scope is disposed, that service may point to disposed state.
It is like taking an ice cube out of the freezer for later; by the time you need it, it has melted.
Install
dotnet add package DependencyInjection.Lifetime.Analyzers --version 2.8.26
README problem example
public IMyService GetService()
{
using var scope = _scopeFactory.CreateScope();
return scope.ServiceProvider.GetRequiredService<IMyService>();
}
README better pattern
public void UseServiceNow()
{
using var scope = _scopeFactory.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<IMyService>();
service.Execute();
}
Repo sample extraction
Sample app warning case
public IScopedService Bad_ServiceEscapesViaReturn()
{
using var scope = _scopeFactory.CreateScope();
// DI002: Service resolved from scope escapes via 'return'
return scope.ServiceProvider.GetRequiredService<IScopedService>();
}
Sample app safe pattern
public void Good_UsedWithinScope()
{
using var scope = _scopeFactory.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<IScopedService>();
service.DoWork(); // Used within scope - OK
}
Related guides
More documentation