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.
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.2.2
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