الانتقال إلى المحتوى
.NETASP.NET Core· 8 دقائق للقراءة

Singleton, Scoped, Transient: The Captive Dependency Trap in ASP.NET Core

A singleton keeps every dependency it was built with, so a scoped DbContext inside it is shared by every request. What breaks, what the scope check catches, and what it misses.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

A pull request changes one line: AddScoped<PriceService>() becomes AddSingleton<PriceService>(). The reasoning sounds fine. The class keeps no state of its own, it runs on every product page, and one instance is cheaper than one per request. The unit tests pass, because they build PriceService with new. Production starts without complaint. A day later, two bug reports arrive: price changes made in the admin panel no longer show on product pages, and under load some requests fail with "A second operation was started on this context instance before a previous operation completed". Nobody touched the database code.

The common misconception

The belief: a is a performance knob. Singleton saves allocations, transient costs a few, scoped sits in between, and any service can depend on any other because the container wires them up either way.

It's an easy belief to hold. The lifetime docs do talk about cost: a transient service "incurs per-request allocations". A class whose only field is an injected dependency really does look stateless. And in production the container accepts the registration silently, so nothing suggests that a rule was broken.

The hidden assumption is that a class is stateless when its own code holds no state. Its dependencies count too. PriceService holds a ShopDb, and a DbContext is full of state: a change tracker, the operation in progress, a connection. Microsoft's guidelines actually point the other way: use a singleton only for a service whose own state is expensive to create or meant to be shared, and avoid it for services with no state, which are cheap to create as transients.

What actually happens

A singleton is built once, with everything it asks for

The container creates a singleton the first time it's requested and returns that same instance for the rest of the app's life. Its constructor runs once, so each dependency is resolved once and stored in a field. Whatever lifetime that dependency was registered with, it now lives exactly as long as the singleton. That's a : a longer-lived service holding a shorter-lived one captive.

The captive comes from the root scope, not from a request

You might expect the singleton to keep the first request's instance. It doesn't. A singleton is resolved from the root provider, so its scoped dependencies come from the root scope, which no request ever uses. In a test, a middleware stored each request's tenant in a scoped TenantContext, and a singleton that injected TenantContext saw null on every request. The docs describe the result: a scoped service created in the root container is effectively promoted to a singleton, and it's disposed only when the app shuts down.

What that does to a DbContext

A DbContext is designed for one short unit of work, and it isn't thread-safe. Shared by every request, it fails in three ways:

  • Concurrent use throws. In a test with 200 parallel requests on one captured context, 169 failed with the "second operation" exception.
  • Reads go stale. FindAsync returns an entity the context already tracks without asking the database. In the same setup, a price that another request changed to 12 still read as 10.
  • Memory only grows. Every tracked entity stays in the change tracker until the app stops.

The one-line bug, fixed

Both versions use the same ShopDb context with a Products set:

C# Program.cs
var builder = WebApplication.CreateBuilder(args);builder.Services.AddDbContext<ShopDb>();// "It keeps no state, so a singleton is cheaper"builder.Services.AddSingleton<PriceService>();var app = builder.Build();app.MapGet("/products/{id:int}/price",    async (int id, PriceService prices) => await prices.GetAsync(id));app.Run();public sealed class PriceService(ShopDb db){    // One ShopDb from the root scope, shared by every request    public async Task<decimal?> GetAsync(int id) =>        (await db.Products.FindAsync(id))?.Price;}

Hosted services are where you can't just change the lifetime, because AddHostedService registers a singleton. Don't inject the context there. Inject IServiceScopeFactory and create a scope for each unit of work:

C# SaleExpiry.cs
using Microsoft.EntityFrameworkCore;public sealed class SaleExpiry(IServiceScopeFactory scopes) : BackgroundService{    protected override async Task ExecuteAsync(CancellationToken ct)    {        using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5));        while (await timer.WaitForNextTickAsync(ct))        {            // One scope per run: a fresh ShopDb, disposed when the run ends            await using var scope = scopes.CreateAsyncScope();            var db = scope.ServiceProvider.GetRequiredService<ShopDb>();            await db.Products.Where(p => p.SaleEndsAt < DateTime.UtcNow)                .ExecuteUpdateAsync(s => s.SetProperty(p => p.OnSale, false), ct);        }    }}

What the scope check catches

In the Development environment, WebApplication.CreateBuilder turns on two checks: ValidateScopes rejects scoped services resolved from the root or consumed by a singleton, and ValidateOnBuild builds every registration at startup. Tested on .NET 10, together they catch some shapes and miss others:

How the singleton gets the scoped serviceDevelopmentProduction
A constructor parameterStartup fails: "Cannot consume scoped service 'ShopDb' from singleton 'PriceService'"Starts, shares one instance
Through a transient in betweenStartup fails, naming the transientStarts, shares one instance
A factory lambda or an injected IServiceProviderStarts; first use throws "Cannot resolve scoped service ... from root provider"Starts, shares one instance
A transient with mutable stateNot detectedNot detected

The last row is a reminder that validation only knows about scopes. The guidelines say a transient used by a singleton may need to be thread-safe, depending on how the singleton uses it. In the test, a transient counter captured by a singleton kept counting across requests in both environments.

How to apply it in your project

  1. Turn on both checks outside DevelopmentEnable ValidateScopes and ValidateOnBuild in staging and in your integration tests, or in every environment. Constructor captives then fail before any traffic arrives.
  2. Default to scoped near requests and databasesServices that use a DbContext, repositories and anything holding per-user data are scoped. Make a service a singleton only when it's thread-safe and holds state meant to be shared, such as a cache.
  3. Give singletons their own scopesIn a BackgroundService or any singleton that needs scoped work, inject IServiceScopeFactory, call CreateAsyncScope per unit of work, and resolve scoped services from that scope.
  4. Search for the shapes validation can't seeSearch for AddSingleton(sp => and for IServiceProvider in singleton constructors, and check what they resolve. Then look at singletons that hold transients with mutable fields.

Key takeaways

  • A lifetime decides who shares an instance and for how long; performance is a side effect.
  • A singleton's dependencies are resolved once, from the root scope, and live as long as it does, whatever their own lifetime.
  • A captured DbContext is shared by every request: concurrent calls throw, tracked data goes stale, memory grows.
  • Development rejects constructor captives at startup; production checks nothing unless you turn on ValidateScopes.
  • Factories, IServiceProvider and stateful transients get past startup checks, so keep every service no longer-lived than its dependencies.

📚 المصادر

  1. Service lifetimes (dependency injection) — Microsoft Learn
  2. Dependency injection guidelines — Microsoft Learn
  3. Dependency injection in ASP.NET Core — Microsoft Learn
  4. Dependency injection in .NET: Scope validation — Microsoft Learn
  5. DbContext lifetime, configuration, and initialization — EF Core, Microsoft Learn

التعليقات (0)