Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 2 · Lesson 15 · 7 min read

ASP.NET Core DI Lifetimes: Scoped vs Singleton

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Leaky Singleton, a Captive Dependency and a Typed Client
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Choose the correct lifetime for common web services, recognize and prevent captive dependencies and shared-state bugs, use IHttpClientFactory instead of creating HttpClient instances by hand, and explain how a singleton that holds per-user data becomes a data leak between users.

Concept Explanation

In Day 8 you met transient, scoped, and singleton lifetimes. In a web application the distinction has real consequences because many requests run at the same time in one process. Scoped services are created once per request and disposed when it ends, which makes them safe for state belonging to that request. The database context, the current user accessor, and unit-of-work objects are scoped. Singletons live for the entire process and are shared by every concurrent request, so they must be thread-safe and must hold only data that is legitimately global, such as configuration, compiled patterns, and caches keyed carefully.

A captive dependency is the classic wiring bug: a longer-lived service holds a shorter-lived one. If a singleton takes a scoped service in its constructor, the singleton captures the first request's instance and keeps using it forever, long after that request ended. For a database context that means a disposed or shared connection object being used by many requests concurrently, which is not thread-safe and produces bizarre intermittent errors. The framework can catch this: in the Development environment it validates scopes by default and throws when it detects the mistake. You can turn on the same checks for builds with ValidateOnBuild. If you truly need scoped work from a singleton, such as in a background service, create a scope explicitly with IServiceScopeFactory.

The most dangerous version of shared-state mistakes is cross-user leakage. Consider a singleton service with a field holding the current user's name or last search, or a static dictionary used as a quick cache keyed by something that is not unique to the user. Two simultaneous requests overwrite each other's data, and one user's information appears in another user's response. There is no exception and no crash, so it can go undetected for a long time. The rules that prevent it are simple: no per-request or per-user state in singletons or static fields, always include the user or tenant in cache keys for user-specific data, and prefer immutable data in shared services.

HttpClient has its own lifetime trap. Creating a new HttpClient for every request and disposing it leaves sockets in the TIME_WAIT state and can exhaust available ports under load, while a single static client keeps connections forever and never notices DNS changes. IHttpClientFactory solves both by pooling and recycling the underlying handlers. You register named or typed clients, set a base address, a timeout, and default headers in one place, and inject them. It also plugs into resilience policies such as retries and circuit breakers, which Phase 7 covers. It is a good example of a general rule: when a framework offers a factory for a resource with tricky lifetime rules, use it.

Service typeRecommended lifetimeReason
DbContextScopedNot thread-safe, tracks changes for one unit of work
Current user accessorScopedDepends on the request
Application configuration, compiled RegexSingletonImmutable and identical for everyone
In-memory cacheSingletonShared by design, keys must isolate users
HttpClientVia IHttpClientFactoryManages handler pooling and DNS refresh
Stateless helper or mapperSingleton or transientNo state, so either is safe

Worked Example: A Leaky Singleton, a Captive Dependency and a Typed Client

The first block shows a singleton that leaks data between users. The second shows scope validation catching a captive dependency, plus the safe pattern for background work. The third registers a typed HttpClient.

C#
// LEAKY: a singleton with per-request state. Two concurrent requests overwrite each other.
public sealed class RecentSearchService
{
    private string _lastSearch = "";                    // shared by every user
    public void Record(string term) => _lastSearch = term;
    public string Last() => _lastSearch;                // may return another user's search
}
builder.Services.AddSingleton<RecentSearchService>();

// FIXED: key the data by user, or keep it scoped and stateless.
public sealed class RecentSearchService
{
    private readonly ConcurrentDictionary<string, string> _byUser = new();
    public void Record(string userId, string term) => _byUser[userId] = term;
    public string? Last(string userId) => _byUser.GetValueOrDefault(userId);
}
C#
// CAPTIVE DEPENDENCY: singleton captures a scoped DbContext.
builder.Services.AddDbContext<AppDb>(/* scoped by default */);
builder.Services.AddSingleton<ReportCache>();           // constructor takes AppDb: wrong

// In Development, scope validation fails fast at startup or first use.
// Enable it explicitly for every environment in tests and builds:
builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; });

// Correct way for a singleton or background service to use scoped services:
public sealed class NightlyJob(IServiceScopeFactory scopes) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var scope = scopes.CreateScope();          // fresh scope for this unit of work
        var db = scope.ServiceProvider.GetRequiredService<AppDb>();
        // ... use db, then the scope disposes it
    }
}
C#
// A typed client: configured once, injected where needed, handlers managed by the factory.
public sealed class WeatherClient(HttpClient http)
{
    public Task<Forecast?> GetAsync(string city, CancellationToken ct) =>
        http.GetFromJsonAsync<Forecast>($"forecast?city={Uri.EscapeDataString(city)}", ct);
}

builder.Services.AddHttpClient<WeatherClient>(c =>
{
    c.BaseAddress = new Uri("https://api.weather.example/");
    c.Timeout = TimeSpan.FromSeconds(10);
});

Notice Uri.EscapeDataString on the user-supplied city. Concatenating untrusted values into a URL without encoding lets a caller inject extra path or query components into the outbound request, a mistake that grows into server-side request forgery when the whole URL is user controlled.

A singleton that takes a scoped DbContext captures the first request instance forever. The safe pattern creates a fresh scope per unit of work with IServiceScopeFactory.
A singleton that takes a scoped DbContext captures the first request instance forever. The safe pattern creates a fresh scope per unit of work with IServiceScopeFactory.

Real-World Examples

  • In March 2023, OpenAI took ChatGPT offline briefly after a bug in an open-source Redis client library caused some users to see titles from other users' conversations and, for a small share of subscribers, limited payment-related details. OpenAI's postmortem traced it to shared connection state returning responses to the wrong requester, a vivid demonstration that leaks between users come from shared-state bugs and not only from missing access checks.
  • Microsoft introduced IHttpClientFactory in ASP.NET Core 2.1 specifically to resolve socket exhaustion from creating and disposing HttpClient repeatedly and stale DNS from long-lived instances. The official guidance now treats manual creation of HttpClient per request as an anti-pattern for server applications.
Key TakeawaysScoped services hold per-request state and singletons hold thread-safe global data, so choosing the right lifetime matters. A singleton that depends on a scoped service is a captive dependency that scope validation will catch. Never store per-user data in singletons or statics without keying it by user, and get HttpClient instances from IHttpClientFactory rather than creating them yourself.

Review Questions & Answers

It is a long-lived service, usually a singleton, holding a reference to a shorter-lived one, such as a scoped database context. The short-lived instance is created once and reused across requests long after it should have been disposed, causing concurrent access to a non-thread-safe object, stale data, and intermittent errors that are hard to reproduce. Enabling scope validation turns it into an immediate startup failure.

If it stores per-request or per-user data in an instance field, all concurrent requests share that one field, so a value written for one user can be read by another before it is overwritten. Since nothing fails, the wrong data is simply returned, and the flaw may be noticed only through a complaint or an incident. The prevention is to keep such data out of singletons or key it explicitly by user.

Each new instance opens fresh connections, and disposing it leaves sockets in a waiting state, so high request rates can exhaust available ports. A single long-lived instance reuses connections but may keep using a stale IP address after DNS changes. IHttpClientFactory manages a pool of handlers and recycles them periodically, avoiding both problems.

Inject IServiceScopeFactory into the background service, create a scope for each unit of work, and resolve the context from that scope, disposing the scope when done. Injecting the scoped context directly into a hosted service would capture a single instance for the life of the application. Creating a scope per iteration mirrors what a web request does.