DI001

Service Scope Not Disposed

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.

Warning Default severity · Code fix: Yes

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.

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

Yes. Adds using / await using where possible; the await using conversion also rewrites explicitly typed declarations to var, because AsyncServiceScope boxed to IServiceScope cannot be awaited-using.

Repo sample extraction

Examples pulled from the sample app

Open full sample file

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

Nearby diagnostics

Other rules in this family

All 37 rules