DI002

Scoped Service Escapes Scope

a service resolved from a scope that is returned or stored somewhere longer-lived.

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 and acknowledgement options where direct refactor is not safe).

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
    }