DI002

Scoped Service Escapes Scope

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.

Default severity: Warning · Code fix: Yes

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.

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

Yes (suppression option for intentionally accepted cases where direct refactoring is not practical).

Repo sample extraction

Examples pulled from the sample app

Open full sample file

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
    }