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
| Lifetime | One instance per | Typical use |
|---|---|---|
AddTransient | Every resolution | Lightweight, stateless services |
AddScoped | HTTP request (scope) | DbContext, unit of work, per-request state |
AddSingleton | Application | Configuration, 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 servicesCaptive 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.