DI Lifetimes Cheat Sheet: Transient, Scoped, Singleton and Captive Dependencies
Choose transient, scoped and singleton lifetimes.
The three .NET dependency injection lifetimes (transient, scoped, singleton), the captive dependency bug, how scope validation catches it, and how a singleton or a background service uses scoped services safely.
At a glance
- A lifetime says how long the container hands out the same instance: transient = a new one each time, scoped = one per scope (an HTTP request in ASP.NET Core), singleton = one for the app.
- A singleton must not hold a scoped service: a singleton holding a scoped
DbContextis a captive dependency. A transient held by a singleton lives as long as the singleton, which is fine only if it is safe to share across threads. - Scope validation catches singleton-to-scoped dependencies and scoped services resolved from the root. ASP.NET Core and the generic host turn it on in Development only.
- In a singleton or a
BackgroundService, injectIServiceScopeFactoryand create one scope per unit of work. - The container disposes what it creates, when the scope (or the app) ends; not instances you created and registered yourself.
AddDbContextregisters the context as scoped.
The three lifetimes
| Lifetime | Registration | One instance per | Typical use | Watch out for |
|---|---|---|---|---|
| transient | AddTransient<IFoo, Foo>() | resolve | light, stateless services | a disposable transient resolved from the root lives until the app ends |
| scoped | AddScoped<IFoo, Foo>() | scope (an HTTP request in ASP.NET Core) | DbContext, unit of work, request state | resolving it from the root; sharing it across threads |
| singleton | AddSingleton<IFoo, Foo>() | app | caches, clocks, configuration access | must be thread-safe; its dependencies live as long as it does |
Who may depend on whom
| Consumer ↓ / dependency → | transient | scoped | singleton |
|---|---|---|---|
| transient | yes | yes, within the scope | yes |
| scoped | yes | yes | yes |
| singleton | allowed, but the transient now lives as long as the singleton | captive dependency: rejected by scope validation | yes |
Scope validation does not flag a singleton holding a transient; that is still a bug when the transient is not meant to be shared or thread-safe.
Scope validation
ValidateScopes = true: throws when a scoped service is resolved from the root provider, or when a singleton depends on a scoped service.ValidateOnBuild = true: checks the registrations when the provider is built, so a detectable captive dependency fails at startup. It does not run factory delegates, and open generics are skipped.WebApplication.CreateBuilderandHost.CreateApplicationBuilderturn both on in the Development environment only, so test there or set them yourself.
The rules in one program
This example needs the Microsoft.Extensions.DependencyInjection package (10.0.12), so it does not run on this site's runner. It was built and run locally with the package; the output below is what it printed.
using Microsoft.Extensions.DependencyInjection;
var options = new ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true };
var services = new ServiceCollection();
services.AddTransient<TransientDep>();
services.AddScoped<ScopedDep>();
services.AddSingleton<SingletonDep>();
using var root = services.BuildServiceProvider(options);
using (var scopeA = root.CreateScope())
using (var scopeB = root.CreateScope())
{
IServiceProvider a = scopeA.ServiceProvider, b = scopeB.ServiceProvider;
Console.WriteLine($"transient, same in one scope: {Same<TransientDep>(a, a)}");
Console.WriteLine($"scoped, same in one scope: {Same<ScopedDep>(a, a)}");
Console.WriteLine($"scoped, same across scopes: {Same<ScopedDep>(a, b)}");
Console.WriteLine($"singleton, across scopes: {Same<SingletonDep>(a, b)}");
}
try { root.GetRequiredService<ScopedDep>(); } // scoped from the root
catch (InvalidOperationException) { Console.WriteLine("scoped from the root: InvalidOperationException"); }
var captive = new ServiceCollection();
captive.AddScoped<ScopedDep>();
captive.AddSingleton<CaptiveSingleton>(); // singleton -> scoped
try { captive.BuildServiceProvider(options); }
catch (AggregateException ex) { Console.WriteLine($"captive dependency at build: {ex.InnerExceptions[0].GetType().Name}"); }
static bool Same<T>(IServiceProvider x, IServiceProvider y) where T : notnull =>
ReferenceEquals(x.GetRequiredService<T>(), y.GetRequiredService<T>());
sealed class TransientDep;
sealed class ScopedDep;
sealed class SingletonDep;
sealed class CaptiveSingleton(ScopedDep dep) { public ScopedDep Dep { get; } = dep; }transient, same in one scope: False scoped, same in one scope: True scoped, same across scopes: False singleton, across scopes: True scoped from the root: InvalidOperationException captive dependency at build: InvalidOperationException
A scope per unit of work
public sealed class OutboxWorker(IServiceScopeFactory scopeFactory) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await using (var scope = scopeFactory.CreateAsyncScope()) // a fresh DbContext per batch
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// ... one batch of work ...
await db.SaveChangesAsync(stoppingToken);
}
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
}- One scope per message or batch: one scope for the worker's whole life recreates the captive dependency.
- Use
CreateAsyncScope()withawait usingwhen a scoped service isIAsyncDisposable, asDbContextis. - A
DbContextis not thread-safe: parallel work needs separate scopes.
Other facts interviewers ask
- Several registrations:
GetService<IFoo>()returns the last one registered;GetServices<IFoo>()returns all, in order.TryAdd*registers only when the service type is not registered yet. - Keyed services (.NET 8):
AddKeyedScoped<IFoo, Foo>("blue"), injected with[FromKeyedServices("blue")]. - Options:
IOptions<T>is computed once;IOptionsSnapshot<T>is scoped, so a singleton must not take it;IOptionsMonitor<T>is a singleton that sees reloads. - Middleware: conventional middleware is created once, so take scoped services as parameters of
InvokeAsync, not in its constructor. - HttpClient: use
IHttpClientFactoryor typed clients. A typed client is transient; captured in a singleton, it keeps its handler longer than the factory intends.
Common mistakes
- A singleton cache that takes
AppDbContextin its constructor: every request shares one context. Create a scope per operation, or make the cache scoped. app.Services.GetRequiredService<AppDbContext>()at startup: create a scope first,using var scope = app.Services.CreateScope();.- A
BackgroundServicethat creates one scope and loops inside it forever: create a scope per message or batch. - Work started with
Task.Runthat keeps using request services after the request ended: their scope is disposed, so it can fail, often withObjectDisposedException. Give that work its own scope. IServiceProviderinjected everywhere as a service locator: hidden dependencies escape the build-time check. Inject what the class needs.- Running only in Production during tests: validation is off there; turn it on in test hosts too.
In an interview
What is a captive dependency, and which one does the built-in container detect? A longer-lived service holding a shorter-lived one, so the shorter-lived one outlives its scope. With scope validation on, the container rejects a singleton that depends on a scoped service; it does not flag a singleton holding a transient.
Why does a captive dependency work in a demo and fail in production? With one user, a single shared DbContext seems fine. Under load, concurrent requests use it at once, so you get threading exceptions, stale data and a change tracker that keeps growing.
How do you use a DbContext from a BackgroundService? Inject IServiceScopeFactory, create an async scope for each message or batch, resolve the context from that scope, and dispose the scope when the work is done.
What does ValidateOnBuild add to ValidateScopes? It checks the registrations when the provider is built, so a detectable captive dependency fails at startup instead of at the first request that resolves it.
Which options interface can a singleton take when configuration reloads? IOptionsMonitor<T>: it is a singleton and returns the current value through CurrentValue. IOptionsSnapshot<T> is scoped and would become a captive dependency.
Who disposes a service, and when? The container disposes the disposable services it created when their scope ends, or when the app ends for singletons. An instance you created yourself and registered with AddSingleton(instance) is yours to dispose.
Check yourself
With scope validation on, a singleton takes a scoped service in its constructor. What happens?
Show answer
Correct answer: B
Scope validation rejects a singleton that depends on a scoped service; with ValidateOnBuild it fails when the provider is built.
Option A: That is what happens without validation, and it is the bug.
Option C: The container never creates scopes on its own for a singleton.
Option D: Scope validation rejects the dependency before anything is injected.
How should a BackgroundService use a DbContext?
Show answer
Correct answer: C
A scope per message or batch gives each unit of work its own context, disposed when the work ends.
Option A: A hosted service is a singleton, so this captures the context forever.
Option B: One scope for the whole worker is still a captive context.
Option D: Resolving scoped services from the root is what scope validation rejects.
Which lifetime gives a new instance every time the service is resolved?
Show answer
Correct answer: A
A transient service is created for each resolve.
Option B: Scoped gives one instance per scope.
Option C: Singleton gives one instance for the app.
Option D: A key selects a registration; it is not a lifetime.
Related on TechInterviewNotes
- Inside the DI Container: Lifetimes, Scopes, Disposal and Captive Dependencies (ASP.NET Core Internals, lesson 5)
- SOLID with Composition, Dependency Injection, and Honest Boundaries (Learn C# and .NET 10, lesson 12)
- How an ASP.NET Core Request Actually Flows
Sources
- Service lifetimes: transient, scoped and singleton.
- Dependency injection guidelines: captive dependencies, scope validation, disposal.
- Use scoped services within a BackgroundService: a scope per unit of work.
- ServiceProviderOptions:
ValidateScopesandValidateOnBuild. - Dependency injection in ASP.NET Core: validation in Development, middleware and keyed services.
- Options pattern:
IOptions,IOptionsSnapshotandIOptionsMonitor.
TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·