Roadmap › SOLID Principles with Examples › Module: L, I and D
Lessons in this course (8)

6. Dependency injection lifetimes in ASP.NET Core

Intermediate★ Must knowLesson 6 of 8
LifetimeOne instance perTypical use
AddTransientEvery resolutionLightweight, stateless services
AddScopedHTTP request (scope)DbContext, unit of work, per-request state
AddSingletonApplicationConfiguration, caches, HttpClient handlers, thread-safe services
csharp
builder.Services.AddSingleton<IClock, SystemClock>();
builder.Services.AddScoped<IOrderRepository, SqlOrderRepository>();
builder.Services.AddTransient<IEmailBuilder, EmailBuilder>();
builder.Services.AddKeyedSingleton<IPaymentGateway, StripeGateway>("stripe");   // .NET 8 keyed services

Captive dependency bug: a singleton that takes a scoped service (e.g. DbContext) keeps that one instance forever, so it is shared across requests and threads. The default container throws in Development (ValidateScopes). Fix: inject IServiceScopeFactory and create a scope, or change the lifetimes.