Skip to content

.NET DI Lifetimes: Avoiding Captive Dependencies and Scoping Pitfalls

Practical guidance to register and consume services correctly in .NET: lifetimes, scope validation, hosted services, and background work patterns.

Ekanatha Reddy Urivakili12 min2,076 words

Why Lifetimes Matter in .NET Dependency Injection

Dependency Injection (DI) is a fundamental architectural pattern in .NET applications, allowing for loose coupling and improved testability. The DI container is responsible for managing object lifetimes and disposal. However, mismatching lifetimes often leads to subtle bugs that are hard to diagnose, such as resource leaks, stale state, and thread-safety issues.

A classic problem is the captive dependency: when a singleton service captures a dependency registered with a shorter lifetime, typically scoped or transient. Since the singleton lives for the application's lifetime, the scoped/transient service effectively becomes a singleton, retaining unintentional state or references.

What Happens When Lifetimes Are Misused?

  • Singleton holding a Scoped service
    The scoped service is promoted to singleton scope, potentially causing:

    • Stale database contexts or cached data that never refresh
    • Resource leaks (e.g., unclosed DB connections)
    • Thread safety issues (services designed for one request used globally)
  • Scoped service injecting a Transient with disposable dependencies
    Can cause disposal issues if transient instances depend on resources that are disposed prematurely or shared incorrectly.

Lifetimes in .NET DI

LifetimeDescriptionTypical Use Cases
SingletonCreated once, reused for app lifetimeLogging, configuration, caching
ScopedCreated once per scope (e.g., per HTTP request)DbContext, Unit of Work, per-request services
TransientCreated each time requestedLightweight stateless services

Practical Rules of Thumb for .NET DI Lifetimes

  • Register DbContexts as scoped
    DbContext is designed to be short-lived and thread-unsafe; use scoped lifetime to match HTTP request or operation scope.

  • Avoid injecting scoped services into singletons
    Instead, inject a factory or IServiceScopeFactory to create scoped lifetimes on demand.

  • Hosted services (background workers) should not directly consume scoped services
    They live for the application lifetime (singleton); access scoped services by creating explicit scopes inside worker loops.

  • Favor constructor injection whenever possible
    It enforces dependencies at object creation and improves code clarity and testability.

  • When resolving services on the fly, create scopes explicitly
    Use IServiceScopeFactory.CreateScope() or IServiceProvider.CreateScope() to produce properly scoped service providers.

High-Level Design Diagram: Lifetimes in Application Context

flowchart LR
  A[Singleton Service] -->|Injects| B[Transient Service]
  A -->|Creates Scope| C[Scoped Service]
  subgraph HTTP Request Scope
    C --> D[DbContext (Scoped)]
    C --> E[Business Service (Scoped)]
  end
  A -. Hidden reference .-> D
  classDef singleton fill:#f9f,stroke:#333,stroke-width:1px;
  classDef scoped fill:#bbf,stroke:#333,stroke-width:1px;
  class A singleton;
  class B singleton;
  class C scoped;
  class D scoped;
  class E scoped;

Diagram showing correctly isolated service lifetimes with scopes created inside singletons for scoped dependencies

Example: Correct Background Worker Using Scoped Services

Background HostedServices are singletons by design, but they frequently need services registered as scoped. The recommended approach is to use IServiceScopeFactory to create scopes inside the worker loop.

public class Worker : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;

    public Worker(IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        while (!ct.IsCancellationRequested)
        {
            using var scope = _scopeFactory.CreateScope();
            var db = scope.ServiceProvider.GetRequiredService<MyDbContext>();

            // Do work with scoped services here
            // Example: process queue messages, update database, etc.

            await Task.Delay(TimeSpan.FromSeconds(5), ct);
        }
    }
}

What to Notice

  • The Worker itself is singleton but creates a new scope per iteration.
  • Scoped services are resolved inside this scope.
  • Properly disposes of scoped services at the end of each iteration.

Common Pitfall: Captive Dependency Example

public class BrokenService
{
    private readonly MyDbContext _dbContext;

    // Injecting scoped DbContext directly into singleton service
    public BrokenService(MyDbContext dbContext)
    {
        _dbContext = dbContext; // Captive dependency: DbContext singleton instance
    }
}

This pattern leads to DbContext behaving as a singleton, lasting beyond its expected lifecycle and causing concurrency and stale data issues.

Recognizing and Fixing Captive Dependencies

IssueSymptomFix
Scoped service injected into singletonStale data, concurrency errorsInject IServiceScopeFactory instead, create scopes on demand
Transient with disposable dependencies captured by scopedPremature disposal, resource leaksUse IServiceScopeFactory or properly scope lifetime
Background service using scoped directlyDbContext reuse across worker runsCreate scope inside worker loops

Validation & Diagnostics in .NET DI

Enable Scope Validation in Development

The .NET Generic Host allows enabling scope validation during service provider build, which catches invalid scoped-in-singleton registrations early:

var host = Host.CreateDefaultBuilder(args)
    .UseDefaultServiceProvider(options =>
        options.ValidateScopes = true)     // Enable validation
    .Build();

This will throw exceptions during app startup if a scoped service is injected into singleton without using factories.

Service Registration Audits

For large codebases, consider:

  • Using Roslyn analyzers or IDE plugins to detect lifetime mismatches.
  • Custom diagnostic tools auditing registrations through reflection or service metadata.
  • CI/CD pipeline checks to enforce DI best practices.

Observability: What to Log and Monitor for DI Lifetime Issues

  • Logging:
    • Log service resolution errors related to lifetime mismatches.
    • Instrument background workers’ scope creation lifecycle.
    • Explicitly log disposal of scoped services.

Structured log example:

{
  "Timestamp": "2024-06-01T10:12:34Z",
  "Level": "Error",
  "Category": "Microsoft.Extensions.DependencyInjection",
  "EventId": 1001,
  "Message": "Scoped service 'MyScopedService' injected into singleton 'MySingletonService'.",
  "StackTrace": "...",
  "ScopeId": "abc123"
}
  • Metrics: Use RED (Request, Error, Duration) metrics for services handling requests/scopes, and USE (Utilization, Saturation, Errors) for underlying resources like threads and connection pools.
MetricDescriptionTarget
RequestsNumber of service activationsMatch expected load
ErrorsFailed service resolutionsNear zero
DurationTime taken to create/resolve servicesMinimal/consistent
UtilizationResource usage (thread, CPU)Below threshold (e.g., 70%)
SaturationResource queue length or contentionMinimal

Distributed Tracing with OpenTelemetry

Instrument DI scopes and service resolutions to observe dependency chains and latencies:

// Configure OpenTelemetry tracing with .NET DI
services.AddOpenTelemetryTracing(builder =>
{
    builder
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddSource("MyApplication.Worker") // Add your app sources for tracing
        .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("MyAppService"));
});

// Trace usage example in background worker
public class Worker : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly ActivitySource _activitySource = new ActivitySource("MyApplication.Worker");

    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        while (!ct.IsCancellationRequested)
        {
            using var activity = _activitySource.StartActivity("BackgroundWorkerIteration");
            using var scope = _scopeFactory.CreateScope();

            var db = scope.ServiceProvider.GetRequiredService<MyDbContext>();

            // perform work

            await Task.Delay(5000, ct);
        }
    }
}

Internals of .NET DI Container Lifetimes and Captive Dependency Mechanics

Understanding how the .NET DI container implements lifetimes internally demystifies why certain lifetime mismatches cause issues like captive dependencies. This knowledge also aids in debugging and optimizing service lifecycles.

Object Lifecycle and Caching in Microsoft.Extensions.DependencyInjection

  • Singletons are instantiated once and cached for the application's lifetime in the root container's cache dictionary keyed by service type.
  • Scoped services are cached per IServiceScope, which creates a child container with its own cache dictionary.
  • Transient services do not use caching and create new instances on every GetService or GetRequiredService call.

When a service is resolved, the DI container:

  1. Looks for an existing instance in the current scope's cache.
  2. If absent, invokes the factory/delegate (or constructor injector) to create a new instance.
  3. Caches the created instance if service lifetime is singleton or scoped.
  4. Returns the instance.

The Root Cause of Captive Dependencies

If a scoped or transient dependency is resolved during a singleton's constructor (root scope), the dependency is:

  • Created in the root scope instead of a child scope
  • Cached and held strongly by the singleton (because constructor-injected)
  • Therefore lives throughout the application's lifetime — effectively a singleton instance

This breaks assumptions about scoped services like DbContext being per request, causing stale data and concurrency issues.

flowchart TD
    RootScope["Root ServiceProvider (Singleton cache)"]
    ChildScope["Child IServiceScope (Scoped cache)"]

    RootScope -->|Resolve Singleton| SingletonInstance
    SingletonInstance -->|Constructor Injection| ScopedService
    note right of ScopedService ["ScopedService cached in RootScope — Captive dependency occurs"]

    RootScope -->|Resolve Scoped Service| ScopedAtRoot
    ChildScope -->|Resolve Scoped Service| ScopedAtChild

Diagram illustrating scoped service created and cached incorrectly in root scope

Disposing Captive Dependencies

The DI container disposes services when the scope that created them is disposed:

  • Root scope is never disposed until application shutdown (singleton lifetime)
  • Scoped instances are disposed when their scope ends (e.g., HTTP request)

Consequently, if a scoped service is promoted to root scope via a captive dependency, it lives forever and can retain unmanaged resources, resulting in memory and resource leaks.

Captive Dependency in Transient Dependencies

Transients are expected to be short-lived and get disposed at the end of scope lifetime if IDisposable. But if a transient is injected into a scoped service, and the scoped service is resolved at root scope incorrectly, disposal and lifetime assumptions are violated.


Real-World End-to-End Scenario: Handling Scoped DbContext in Background Worker

Background workers in ASP.NET Core apps are singletons and do not have an ambient HTTP request scope. They must manually create service scopes and resolve scoped services inside them to avoid captive dependencies and lifecycle issues.

Problem: Processing a Queue with a Scoped DbContext

An application has a background worker consuming messages from a queue, updating records in a database using Entity Framework Core DbContext registered as scoped.

Naive implementation:

public class QueueProcessor : BackgroundService
{
    private readonly MyDbContext _dbContext;

    public QueueProcessor(MyDbContext dbContext)
    {
        _dbContext = dbContext; // Captive Dependency!
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var message = await DequeueMessageAsync(stoppingToken);
            _dbContext.Entities.Add(TransformMessage(message));
            await _dbContext.SaveChangesAsync(stoppingToken);
        }
    }
}

Issues:

  • MyDbContext is injected as scoped but resolved in singleton constructor.
  • DbContext behaves like singleton, staying alive for worker lifetime.
  • DbContext caches query results and changes tracker indefinitely.
  • Database connections may stay open or leak.
  • Concurrent background processing may cause threading violations on a thread-unsafe DbContext.

Corrected Implementation: Scope Per Message Processing

public class QueueProcessor : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;

    public QueueProcessor(IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            using var scope = _scopeFactory.CreateScope();

            var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>();

            var message = await DequeueMessageAsync(stoppingToken);

            dbContext.Entities.Add(TransformMessage(message));
            await dbContext.SaveChangesAsync(stoppingToken);
        }
    }
}

What This Fixes:

  • New scope created per loop iteration.
  • Scoped DbContext properly created and disposed each iteration.
  • No captive dependency; DbContext lifecycle confined to message processing.
  • Database connections are released promptly.
  • Thread-safety maintained.

Edge Cases, Failure Modes and Lifetime Pitfalls

Container lifetime issues often sneak in under peculiar conditions. Anticipate these edge cases:

1. Mixed Lifetimes with Factory Delegates Capturing Scoped Instances

Factories capturing scoped instances and reused in longer-lived scopes also cause captive dependencies.

services.AddSingleton<Func<MyService>>(provider =>
{
    var scopedService = provider.GetRequiredService<MyScopedService>(); // captive dependency
    return () => new MyService(scopedService);
});
  • scopedService resolved at root scope and becomes effectively singleton.
  • Factory closes over this scoped instance causing unintended sharing.

Fix: Resolve scoped dependencies inside the factory delegate invocation (lazy), not during factory registration.

services.AddSingleton<Func<MyService>>(provider =>
{
    return () =>
    {
        using var scope = provider.CreateScope();
        var scopedService = scope.ServiceProvider.GetRequiredService<MyScopedService>();
        return new MyService(scopedService);
    };
});

2. Dispose Order Issues in Combined Scoped/Transient Registrations

Transients implementing IDisposable created inside a scope but escaping disposal or being captured by scoped objects might cause premature disposal or resource leaks.

Be explicit about disposal expectations for transient disposable services:

  • Inject factory and resolve transient when needed.
  • Avoid caching transient disposables inside longer-lived services unless you manage disposal explicitly.

3. Double Disposal or Missing Disposal

When services with nested lifetimes or multi-layered factories dispose underlying resources incorrectly, disposal can be missed or duplicated.

Use container-scoped lifetimes wherever possible, avoid mixing manual disposal with container disposal mechanisms.

4. ThreadSafety and Async Disposal

  • Ensure scoped services like DbContext are used only within one logical operation (e.g., single HTTP request or scope).
  • Avoid sharing scoped services across multiple threads simultaneously.
  • Dispose async (IAsyncDisposable) properly inside scope disposal.

Edge Case Summary Table

Edge CaseCauseImpactMitigation
Captive Dependency via FactoryFactory captures scoped at root scopeScoped becomes singletonLazy resolve scoped inside factory
Transient disposal escapes scopeTransient disposable cached in scopedPremature or missing disposalCreate fresh transient inside scope / factory
Scope disposed but services reusedManual disposal overlaps containerDouble disposal or exceptionsLet container manage disposal
Scoped service used across threadsCross-thread sharingThread-safety violationsRestrict scoped usage to single logical flow
Async services disposed synchronouslyIgnoring IAsyncDisposableResource leaks, incomplete cleanupImplement async disposal and use await using

Observability for Lifetime and Captive Dependency Problems

Observability here is crucial to detect and diagnose lifetime-related issues early before they impact production.

What to Log

  • Service resolution errors and exceptions, including stack traces
  • Detection of captive dependencies (user code can introduce checks via ValidateScopes)
  • Disposal logs with service type, scope ID, and timestamps.
  • Background worker loop iterations with created/disposed scopes and scoped service resolutions.
  • Unexpected lifetime promotions or reuse detected via custom telemetry or middleware.

Structured Log Example for Disposal

{
  "Timestamp": "2024-06-01T14:22:34Z",
  "Level": "Information",
  "Category": "MyApp.DependencyInjection",
  "EventId": 3001,
  "Message": "Disposed scoped service 'MyDbContext' in scope 'scope-xyz123'",
  "ServiceType": "MyApp.Data.MyDbContext",
  "ScopeId": "scope-xyz123"
}

Essential Metrics (Use RED and USE)

MetricTypeDescriptionSuggested SLI/SLO
Service ResolutionsCounterNumber of service resolutions by lifetimeStable resolution rate matching load
Resolution FailuresCounterNumber of DI resolution failures (exceptions)Near zero (alert if error rate > 0.1%)
Service Resolution DurationHistogramTime spent creating/obtaining service instance< 50ms 95th percentile
Scope Creation RateCounterNumber of scopes created per time intervalMatches application architecture patterns
Memory UsageGaugeHeap / native memory usageBelow threshold
Thread Pool SaturationGaugeThread pool queue length or starvation signBelow 70% utilization

Distributed Tracing Best Practices

  • Instrument scope creation and disposal with meaningful span names (Scope.Create, Scope.Dispose).

  • Correlate DI service resolution spans with business operations and HTTP request spans.

  • Trace background services’ iterations and scoped resolution chains.

  • Add attributes for:

    • Service type being resolved
    • Scope ID or correlation ID
    • Resolution outcome (success/failure)
using var activity = _activitySource.StartActivity("DI.ResolveService");
activity?.SetTag("service.type", typeof(MyDbContext).FullName);

Sample Observability Checklist for DI Lifetimes

CheckpointTool/MethodGoal
Scope Validation EnabledHost builder optionsCatch invalid lifetime injection
DI Resolution Failure LogsApplication logsDiagnose registration errors
Scope Creation/Disposal TelemetryDistributed tracingCorrelate lifetimes and usage
Memory & Connection Pool MetricsPrometheus / App InsightsDetect resource leaks
Background Worker Scope MetricsCustom countersEnsure proper isolation
Automated DI Registration AuditsRoslyn analyzerEnforce lifetime conventions

By drilling into the mechanics of .NET DI lifetimes, you better understand the nature of captive dependencies and how to avoid them. Real production scenarios, edge case awareness, and observability completeness provide the foundation for robust service lifetimes and application stability at scale.

Summary Table: DI Lifetime Strategies in .NET

ScenarioService LifetimeRegistration StrategyNotes
Web API Request HandlingScopedDbContext, business servicesAuto scope per request
Logging ServiceSingletonAddSingletonStateless, reusable
Transient Lightweight ServiceTransientAddTransientFresh instance per injection, no IDisposable
Background Worker ServiceSingletonAddHostedServiceCreate scopes internally for scoped dependencies
Scoped-in-Singleton InjectionInvalidUse IServiceScopeFactoryAvoid captive dependencies

By understanding and correctly implementing lifetimes, you avoid subtle bugs due to premature disposal, resource leaks, or stale state in your .NET DI system. Scoped lifetimes improve robustness and resource management especially in concurrent or background processing contexts.

Remember to enable scope validation during development, audit DI registrations routinely, and leverage structured logging and tracing to maintain reliability and perform root cause analysis effectively.


If you want to dive deeper, consider reading the official Microsoft .NET dependency injection documentation for advanced details on lifetime management and DI patterns.

ShareLinkedInX

Newsletter

Enjoyed this? Get the next one on Saturday.

The week’s new long reads on architecture, cloud and AI — with the diagrams left in. Delivered Saturday morning, no noise in between.

One email every Saturday. Unsubscribe with one click, any time.