Skip to content

Lesson 2 of 9 · 26m

Dependency Injection Lifetimes Without the Landmines

Use singleton, scoped, and transient lifetimes deliberately so services remain correct under concurrent requests and do not capture stale state.

The worst dependency injection bug I ever debugged appeared only on Tuesdays, when the batch importer overlapped with web traffic. A singleton cache was holding a scoped DbContext, which meant one request's entity tracking leaked into another request. It did not fail loudly. It returned slightly wrong data until the object graph grew large enough to fall over. DI is easy to configure and easy to misunderstand.

The three lifetimes are ownership statements

In the built-in container:

services.AddSingleton<IClock, SystemClock>();
services.AddScoped<IOrderRepository, OrderRepository>();
services.AddTransient<IEmailTemplateRenderer, EmailTemplateRenderer>();

Singleton means one instance for the application lifetime. Scoped means one instance per scope, normally one per HTTP request. Transient means a new instance every time the container resolves it. These are not performance knobs first; they are correctness statements about shared state and ownership.

The captive dependency trap

A singleton must not depend on a scoped service. If it does, the scoped service is effectively promoted to singleton and can cross request boundaries:

// Dangerous: singleton captures scoped context.
services.AddSingleton<ReportCache>();
services.AddScoped<AppDbContext>();

public sealed class ReportCache
{
    public ReportCache(AppDbContext db) { /* db is now captive */ }
}

The fix is to inject a factory or scope provider and create a scope only for the duration of the operation:

public sealed class ReportCache
{
    private readonly IServiceScopeFactory _scopeFactory;

    public ReportCache(IServiceScopeFactory scopeFactory) => _scopeFactory = scopeFactory;

    public async Task RefreshAsync(CancellationToken ct)
    {
        using var scope = _scopeFactory.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        // Read only what is needed, then let the scope die.
    }
}

Do not store the scope or the DbContext. Resolve, use, dispose.

HttpClient is the classic lifetime exception

Do not register HttpClient as transient and new it per operation in a busy service. Socket exhaustion used to be the standard failure mode; DNS rebinding and stale connections are the more subtle modern failure. Prefer typed clients through IHttpClientFactory:

builder.Services.AddHttpClient<BillingClient>(client =>
{
    client.BaseAddress = new Uri("https://billing.internal");
    client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
})
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
    PooledConnectionLifetime = TimeSpan.FromMinutes(5)
});

The factory manages handler lifetime separately from the small typed client object.

Constructor injection is a design review

If a constructor has fifteen dependencies, the problem is not the container. The class has too many reasons to change. Group operations behind narrower interfaces, move orchestration upward, or split the service. Also avoid injecting IServiceProvider everywhere; service-location hides the real dependency graph from both reviewers and tests.

Field notes

  • Entity Framework DbContext is scoped for a reason: it tracks state, is not thread-safe, and should not cross concurrent operations.
  • IOptions<T> is singleton-friendly; IOptionsSnapshot<T> is scoped and can capture configuration per request.
  • Scoped services behave differently in background workers because there is no implicit HTTP scope. Create scopes explicitly.
  • Disposal ordering matters. Objects resolved from a scope are disposed with that scope, not when your local variable goes out of use.

Was this lesson helpful?

Sign in to rate