
Singleton, Scoped, Transient: The Captive Dependency Trap in ASP.NET Core
- كاتب موثّق
- .NET 10
محتويات المقال
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
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 captive comes from the root scope, not from a request
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
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. FindAsyncreturns 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
ShopDb context with a Products set:
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;}var builder = WebApplication.CreateBuilder(args);builder.Services.AddDbContext<ShopDb>();// No longer-lived than its shortest-lived dependencybuilder.Services.AddScoped<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){ // A fresh ShopDb per request, disposed when the request ends public async Task<decimal?> GetAsync(int id) => (await db.Products.FindAsync(id))?.Price;}AddHostedService registers a singleton. Don't inject the context there. Inject IServiceScopeFactory and create a scope for each unit of work:
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
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:
IServiceProvider | ||
How to apply it in your project
Turn on both checks outside Development Enable ValidateScopesandValidateOnBuildin staging and in your integration tests, or in every environment. Constructor captives then fail before any traffic arrives.Default to scoped near requests and databases Services 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.Give singletons their own scopes In a BackgroundServiceor any singleton that needs scoped work, injectIServiceScopeFactory, callCreateAsyncScopeper unit of work, and resolve scoped services from that scope.Search for the shapes validation can't see Search for AddSingleton(sp =>and forIServiceProviderin 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 DbContextis 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, IServiceProviderand stateful transients get past startup checks, so keep every service no longer-lived than its dependencies.
📚 المصادر
Service lifetimes (dependency injection) — Microsoft Learn Dependency injection guidelines — Microsoft Learn Dependency injection in ASP.NET Core — Microsoft Learn Dependency injection in .NET: Scope validation — Microsoft Learn DbContext lifetime, configuration, and initialization — EF Core, Microsoft Learn
التعليقات (0)