Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Cheat sheets: all cheat sheets

    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 DbContext is 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, inject IServiceScopeFactory and 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.
    • AddDbContext registers the context as scoped.

    The three lifetimes

    LifetimeRegistrationOne instance perTypical useWatch out for
    transientAddTransient<IFoo, Foo>()resolvelight, stateless servicesa disposable transient resolved from the root lives until the app ends
    scopedAddScoped<IFoo, Foo>()scope (an HTTP request in ASP.NET Core)DbContext, unit of work, request stateresolving it from the root; sharing it across threads
    singletonAddSingleton<IFoo, Foo>()appcaches, clocks, configuration accessmust be thread-safe; its dependencies live as long as it does

    Who may depend on whom

    Consumer ↓ / dependency →transientscopedsingleton
    transientyesyes, within the scopeyes
    scopedyesyesyes
    singletonallowed, but the transient now lives as long as the singletoncaptive dependency: rejected by scope validationyes

    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.CreateBuilder and Host.CreateApplicationBuilder turn 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.

    C#
    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; }
    Output
    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

    C#
    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() with await using when a scoped service is IAsyncDisposable, as DbContext is.
    • A DbContext is 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 IHttpClientFactory or 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 AppDbContext in 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 BackgroundService that creates one scope and loops inside it forever: create a scope per message or batch.
    • Work started with Task.Run that keeps using request services after the request ended: their scope is disposed, so it can fail, often with ObjectDisposedException. Give that work its own scope.
    • IServiceProvider injected 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?

    A It works; the scoped service becomes a singleton
    B The provider throws when it is built or resolved
    C The container creates a new scope for the singleton
    D The scoped service is injected as null
    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?

    A Take the DbContext in its constructor
    B Create one scope at startup and keep it
    C Create a scope per unit of work with IServiceScopeFactory
    D Resolve the context from the root provider
    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?

    A Transient
    B Scoped
    C Singleton
    D Keyed
    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.

    Sources

    TechInterviewNotes Editorial Team · Updated 28 Nov 2026 ·