wasAsked.

Dependency Injection Service Lifetimes – Singleton, Scoped, and Transient

EPAM · Role not specified · technical

Published

Year not specified · .NET, C#

Community answers

Posted by wasAsked editorial collection

Transient creates a new instance on each resolution, scoped creates one per scope (normally one HTTP request), and singleton creates one for the application lifetime. Example: builder.Services.AddTransient<IReceiptFormatter, ReceiptFormatter>(); builder.Services.AddScoped<OrderService>(); builder.Services.AddDbContext<AppDbContext>(); builder.Services.AddSingleton<ISystemClock, SystemClock>(); A singleton must be thread-safe and must not capture a scoped DbContext. A background singleton that needs scoped services should create an IServiceScope per work item. Transient disposable services resolved from the root can remain retained until shutdown. Choose lifetime from ownership and state, and enable scope validation so invalid dependencies fail early.

Backbencher Developer · · 0 likes

Dependency injection (DI) lets a class receive its dependencies instead of creating them. In ASP.NET Core you register services in Program.cs and the built-in container creates them with one of three lifetimes. Singleton — services.AddSingleton<IClock, SystemClock>(); - One instance for the whole application. - Must be thread-safe and should not hold per-user state. - Examples: configuration objects, in-memory caches, IHttpClientFactory, logging. Scoped — services.AddScoped<IOrderService, OrderService>(); - One instance per scope; in web apps that means per HTTP request. - Examples: DbContext (AddDbContext registers it scoped), unit-of-work, current user context. Transient — services.AddTransient<IEmailBuilder, EmailBuilder>(); - A new instance every time it is requested. - Examples: lightweight, stateless helpers. How to choose: - Does it hold state shared by everyone and is it thread-safe? Singleton. - Does it hold state for one request, or depend on DbContext? Scoped. - Is it cheap and stateless? Transient (scoped also works). Common mistakes: - Injecting a scoped service into a singleton (captive dependency). The scoped object lives forever and causes stale data and concurrency bugs. ASP.NET Core detects this in Development with scope validation. - Storing request data in a singleton field, which leaks data between users. - Resolving transient IDisposable services from the root provider, which keeps them alive until shutdown. In background services, create a scope explicitly: using var scope = scopeFactory.CreateScope(); var orders = scope.ServiceProvider.GetRequiredService<IOrderService>();

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics