wasAsked.

Compare scoped, transient, and singleton dependency injection lifetimes in .NET with practical failure examples.

Freshworks · Full Stack Developer · 3-4-years · technical

Published

Year not specified · .NET, C#, ASP.NET Core

Community answers

Posted by wasAsked editorial collection

Transient creates an instance each time the service is resolved. Scoped creates one instance per scope—normally one per ASP.NET Core request. Singleton creates one instance for the application's lifetime and must be thread-safe. ```csharp builder.Services.AddTransient<IReceiptFormatter, ReceiptFormatter>(); builder.Services.AddScoped<OrderService>(); builder.Services.AddDbContext<AppDbContext>(); // scoped by default builder.Services.AddSingleton<ISystemClock, SystemClock>(); ``` A singleton must not directly depend on a scoped DbContext; doing so captures request-specific state beyond its valid lifetime. A singleton with mutable unsynchronized fields can race across requests. A transient disposable service resolved from the root container can remain retained until application shutdown. If a background singleton needs scoped services, create a scope per unit of work: ```csharp await using var scope = scopeFactory.CreateAsyncScope(); var handler = scope.ServiceProvider.GetRequiredService<OrderHandler>(); await handler.RunAsync(stoppingToken); ``` Choose lifetime from ownership and state, not from assumed speed. Validate scopes in development and keep services stateless where practical.

Pooja Parmar · · 0 likes

The three lifetimes control how long the container keeps an instance. - Transient: a new instance every time it is resolved. Use for lightweight, stateless services. - Scoped: one instance per scope — in ASP.NET Core, per HTTP request. Use for per-request state such as DbContext or the current user. - Singleton: one instance for the application's lifetime. Use for thread-safe, stateless or shared resources: configuration, caches, HttpClient handlers via IHttpClientFactory. Practical failure examples: 1. Captive dependency — a singleton depends on a scoped service: services.AddSingleton<ReportService>(); // holds AppDbContext services.AddDbContext<AppDbContext>(); // scoped The singleton keeps the first request's DbContext forever: stale data, thread-safety exceptions and memory growth. ASP.NET Core's scope validation (on by default in Development) throws "Cannot consume scoped service from singleton". Fix: make the consumer scoped or use IServiceScopeFactory / IDbContextFactory. 2. Mutable state in a singleton: public class CartService { public List<Item> Items { get; } = new(); } // registered as singleton Every user shares the same cart. Fix: scoped lifetime or store state per user. 3. Transient IDisposable resolved from the root container: instances are tracked until the app stops, which leaks memory. Resolve within a scope. 4. Creating HttpClient per call (transient, manually) can exhaust sockets. Use IHttpClientFactory, which manages handler lifetimes. Rules of thumb: a service may depend only on services with an equal or longer lifetime; singletons must be thread-safe; enable ValidateScopes and ValidateOnBuild to catch mistakes at startup.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics