wasAsked.

Singleton, Scoped, Transient Lifetimes: Can you walk me through the differences between Singleton, Scoped, and Transient service lifetimes?

Dodge Construction Network · Senior Developer · technical

Published

Asked in 2026 · C#

Community answers

Posted by wasAsked editorial collection

These three lifetimes tell the .NET dependency injection container how often to create a service and how long to keep it. Singleton - One instance for the entire application lifetime, shared by all requests and threads. - Created on first request (or at registration if you pass an instance), disposed at shutdown. - Must be thread-safe and must not hold per-user data. - Examples: configuration and options, IMemoryCache, a Redis ConnectionMultiplexer, a token cache, logging. Scoped - One instance per scope. In ASP.NET Core, each HTTP request gets its own scope, so every class in the same request shares the instance. - Disposed when the request ends. - Examples: EF Core DbContext, unit of work, repositories that use DbContext, a CurrentUser or tenant context. Transient - A new instance every time the service is resolved, even multiple times within one request. - Disposed when the scope that created it ends. - Examples: lightweight stateless helpers, validators, mappers. Walkthrough with two requests - Request 1: OrderController gets OrderService (scoped A) and AppDbContext (scoped A), a new validator (transient) per injection, and the shared clock (singleton X). - Request 2: gets OrderService (scoped B), AppDbContext (scoped B), new validators, and the same clock X. Choosing a lifetime - Does it keep state shared by everyone and is it thread-safe? Singleton. - Does it keep state for one request, or depend on DbContext? Scoped. - Is it stateless and cheap? Transient (or singleton if thread-safe and you want to avoid allocations). Mistakes to avoid - Captive dependency: a singleton depending on a scoped service keeps that scoped instance forever — DbContext concurrency errors and stale data. ASP.NET Core's scope validation catches it in Development. - Storing request or user data in a singleton field (data leaks between users). - Resolving scoped services in background services without creating a scope (use IServiceScopeFactory).

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics