Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson1 / 9

    Module 1 · Runtime, Dependency Injection, and Async Foundations · Lesson 1 of 9

    Dependency Injection Lifetimes and Captive Dependencies

    Diagnose before reading

    A singleton InvoiceDispatcher receives a scoped context. A reviewer proposes putting a lock around the context, then making it singleton if validation still fails. Decide which fix you would reject and sketch the ownership boundary before reading on. This course assumes you can already write async C# and an ASP.NET Core endpoint; use it to rehearse diagnosis and defend a repair, rather than memorize definitions.

    Write your answer first. Then use this trace to check the boundary you chose.

    Trace one unit of workLifetime / ownerQuestion to ask
    Host resolves the workerSingleton hosted serviceDoes it retain request or scoped state?
    Worker begins one invoiceNew async scopeDoes each independently concurrent unit have its own scope/context?
    Handler finishes or throwsScope is disposedIs acknowledgement/retry defined separately from logging?
    Next invoice beginsA different scopeIs any old handler/context still referenced?

    The three built-in lifetimes

    Transient normally creates a new instance for each resolution of a transient registration (a custom registration factory can choose to return an existing object). It fits lightweight, stateless collaborators. Transient does not mean thread-safe, and it does not automatically make an expensive dependency cheap.

    Scoped normally creates one instance per scoped registration within each scope. In ASP.NET Core the request pipeline creates one scope per request. AddDbContext<TContext> registers DbContext as scoped by default. A request can often model a unit of work, but a request may need several units or concurrent operations: use separate contexts where required, and never use the same context concurrently. Scoped is a convention, not a guarantee that work runs in an HTTP request: background services must create scopes explicitly.

    Singleton normally provides one instance per singleton registration in a service provider; building multiple root providers can create separate instances. A singleton can be called concurrently by many requests, so mutable state must be synchronized or avoided. A singleton should not hold request data, DbContext, HttpContext, or another scoped service.

    The captive-dependency failure

    A captive dependency exists when a longer-lived component captures a shorter-lived component. The classic case is a singleton constructor that accepts a scoped repository or DbContext. With scope validation enabled, the app fails during startup or resolution. Without validation, the scoped object may effectively live for the process lifetime, causing stale tracking state, cross-request data leakage, concurrency exceptions, and delayed disposal.

    Incorrect:

    C#
    services.AddScoped<AppDbContext>();
    services.AddSingleton<InvoiceDispatcher>();
    
    public sealed class InvoiceDispatcher
    {
        private readonly AppDbContext _db;
        public InvoiceDispatcher(AppDbContext db) => _db = db;
    }

    The repair is not to change DbContext to singleton. Align ownership with the operation. If dispatching belongs to a request, make InvoiceDispatcher scoped. If it is hosted background work, inject IServiceScopeFactory and create a scope per message or batch.

    C#
    public sealed class InvoiceWorker(
        IServiceScopeFactory scopeFactory,
        ILogger<InvoiceWorker> logger) : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await foreach (var invoiceId in ReadQueueAsync(stoppingToken))
            {
                await using var scope = scopeFactory.CreateAsyncScope();
                var handler = scope.ServiceProvider.GetRequiredService<InvoiceHandler>();
    
                try
                {
                    await handler.ProcessAsync(invoiceId, stoppingToken);
                }
                catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
                {
                    throw; // Preserve normal host shutdown cancellation.
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Invoice {InvoiceId} failed", invoiceId);
                }
            }
        }
    }

    The scope is created for one unit of work and disposed even on failure. Register this worker with AddHostedService<InvoiceWorker>() and register InvoiceHandler and its dependencies with appropriate lifetimes. The hosted worker stays singleton and does not retain scoped objects between iterations. This is an ownership sketch, not a complete queue consumer: ReadQueueAsync and InvoiceHandler.ProcessAsync are application-specific. Scope creation, service resolution, queue enumeration and disposal can also fail; their exceptions are outside the shown handler catch. Logging a processing failure is not a retry or acknowledgement policy. Define acknowledgement, bounded retry/dead-letter behavior and idempotency explicitly so a failed invoice is not silently lost.

    Factories and owned dependencies

    A factory is useful when each operation needs a fresh owned resource. IDbContextFactory<TContext> can provide separate contexts for independent parallel operations, background processing, or UI circuits where a request scope does not model the unit of work; dispose each factory-created context. IHttpClientFactory pools handlers and can rotate them so newly created clients can pick up DNS changes. Its handler-lifetime and connection-pool configuration matter; retaining a factory-created client indefinitely can prevent it from using a replacement handler. Short-lived factory-created HttpClient instances are supported. Avoid wrapping factories only to hide lifetime mistakes.

    Options and state

    With the standard options registrations, IOptions<T> is singleton and caches the default options value; it does not track subsequent configuration changes. IOptionsSnapshot<T> is scoped and lazily computes/caches each named options value when accessed in that scope, typically once per request. IOptionsMonitor<T> is singleton, caches named values and supports change notifications and invalidation when the configuration source supplies reload signals. Capturing IOptionsSnapshot<T> in a singleton repeats the same lifetime error. Prefer IOptionsMonitor<T> when a singleton must observe reloadable configuration, and keep callbacks small and thread-safe.

    Validation that catches problems early

    In development and tests, enable container validation:

    C#
    builder.Host.UseDefaultServiceProvider(options =>
    {
        options.ValidateScopes = true;
        options.ValidateOnBuild = true;
    });

    ValidateOnBuild catches many missing registrations and invalid constructor graphs. ValidateScopes catches singleton-to-scoped capture. Validation does not execute every registration factory or validate open-generic registrations, nor prove concurrency, disposal or business correctness. Add a composition-root test that builds the host and resolves critical entry points in their appropriate scopes.

    Disposal rules

    The built-in container tracks disposable services it creates through type or registration-factory activation and disposes them when the owning scope/provider is disposed. Disposable transients resolved from the root can therefore be retained until root disposal. Do not manually dispose a container-owned injected dependency. If your code creates a disposable object with new, or creates a scope, it normally owns disposal unless ownership is explicitly transferred. Factory ownership depends on the contract: a context from IDbContextFactory<T> is caller-owned, whereas a factory delegate may return a container-owned service that you must not dispose. Registering a pre-created instance leaves its disposal with the caller; a DI registration factory can instead give the container ownership of the object it returns. Dispose asynchronous resources asynchronously where required.

    Interview scenario: tenant-aware cache

    Suppose a singleton cache accepts ITenantContext, which is scoped to the request. This is unsafe even if the cache uses ConcurrentDictionary because the captured tenant identity is the real bug. Pass an authenticated and authorized tenant key into each cache method and partition tenant-specific entries by that key, or store only tenant-neutral state. Do not treat a caller-supplied tenant ID as proof of authorization. Concurrency safety and lifetime correctness are separate concerns.

    Review checklist

    1. Identify the owner and expected lifetime of every dependency.
    2. Ask whether the component can run outside an HTTP request.
    3. Check whether mutable singleton state is thread-safe.
    4. Create and dispose scopes around background units of work.
    5. Never make DbContext singleton to silence scope validation.
    6. Use factories when an operation needs explicit ownership.
    7. Turn on ValidateScopes and ValidateOnBuild in development and integration tests.

    Check the boundary

    A singleton tenant cache uses a ConcurrentDictionary but constructor-injects a scoped ITenantContext. Which repair addresses the lifetime and tenant boundary?

    A Add a lock around dictionary reads only.
    B Register the tenant context as singleton.
    C Pass the verified, authorized tenant key per operation and include it in tenant-specific cache keys; retain no request context.
    D Disable scope validation because the dictionary is thread-safe.
    Show answer

    Correct answer: C

    Dictionary synchronization does not change which tenant context was captured. Per-operation authorized identity and partitioned cache keys address that boundary; the cache still needs an appropriate concurrency and eviction design.

    Hint: Follow the tenant identity, not just the collection type.

    Two-minute interview practice

    Attempt both before comparing. State the assumption, the repair and one limit of your evidence.

    1. Two invoice messages are processed concurrently. Where do you create scopes, and which references must not be shared?
    2. A transient disposable is repeatedly resolved from the root provider. When can it be disposed, and why can memory grow?

    Hint. Revisit the ownership, time, transaction or measurement boundary in the trace table.

    Check your reasoning.

    1. Create one owned scope per independently concurrent unit and resolve a separate scoped handler/context from each. A new scope alone does not make a shared singleton dependency safe. Await each unit and dispose its scope, including failures.
    2. The built-in provider can retain container-created disposable transients until their owning root is disposed. Prefer a bounded scope or an explicitly owned factory result when the ownership contract permits earlier disposal. Merely changing the registration label does not provide early cleanup.

    Evidence for the repair

    A composition-root test should reject the captured graph with both validation flags enabled. Separate behavioral tests must cover concurrent tenant isolation and disposal; container validation cannot prove them.

    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 28 Oct 2026 ·