Why it matters
leads to runtime disposal errors and brittle service behaviour.
It is like trying to turn on a torch after you removed the batteries.
DI004
using a service after the scope that produced it has already ended.
Why it matters
leads to runtime disposal errors and brittle service behaviour.
It is like trying to turn on a torch after you removed the batteries.
Install
dotnet add package DependencyInjection.Lifetime.Analyzers --version 2.2.2
README problem example
IMyService service;
using (var scope = _scopeFactory.CreateScope())
{
service = scope.ServiceProvider.GetRequiredService<IMyService>();
}
service.DoWork();
README better pattern
using (var scope = _scopeFactory.CreateScope())
{
var service = scope.ServiceProvider.GetRequiredService<IMyService>();
service.DoWork();
}
Repo sample extraction
Sample app warning case
public void Bad_UseAfterDispose()
{
IScopedService service;
using (var scope = _scopeFactory.CreateScope())
{
service = scope.ServiceProvider.GetRequiredService<IScopedService>();
}
// DI004: Service 'service' may be used after its scope is disposed
service.DoWork();
}
Sample app safe pattern
public void Good_UsedWithinScope()
{
using (var scope = _scopeFactory.CreateScope())
{
var service = scope.ServiceProvider.GetRequiredService<IScopedService>();
service.DoWork(); // Within scope - OK
}
}
Related guides
More documentation