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

Sign in to add your answer

Related interview topics