DI004

Service Used After Scope Disposed

Using a service after the scope that produced it has already ended, including scoped collections from GetServices<T>() enumerated after disposal, explicit Dispose() / DisposeAsync() (including scope?.Dispose() for scope locals), wrapped use receivers such as service!.DoWork() and ((IService)service).DoWork(), services resolved from a predeclared scope variable later disposed via using (scope), and the same patterns inside constructors, accessors, local functions, lambdas, and anonymous methods. Uses in branches mutually exclusive with the disposal — whether the dispose is explicit or a using statement/declaration — stay quiet, and out arguments are writes rather than uses (the rewritten local is fresh afterwards), while ref arguments still report.

Warning Default severity · Code fix: Yes

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.

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();
}

Yes. Moves simple immediate invocation-style uses back into the owning scope only when the diagnostic local was assigned in that scope, or adds a narrow pragma suppression for context-dependent cases. The pragma suppression always lands on a line-starting statement, so embedded unbraced statements compile.

Repo sample extraction

Examples pulled from the sample app

Open full sample file

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
        }
    }

Nearby diagnostics

Other rules in this family

All 37 rules