Skip to content

C# Interview Guide: DI Service Lifetimes and the Captive Dependency Trap

Q7 — DI Service Lifetimes — Singleton, Scoped, Transient and the Captive Dependency Trap Level: Mid-Level | Topic: ASP.NET Core The Three Lifetimes Singleton: One instance per application. Created once, reused forever. U...

Ekanatha Reddy Urivakili8 min792 words
title: 'C# Interview Guide: DI Service Lifetimes and the Captive Dependency Trap'
excerpt: >-
  Deep dive into C# ASP.NET Core DI lifetimes—Singleton, Scoped, Transient—and how to avoid the common and subtle Captive Dependency Trap with practical code and architecture guidance.
tags:
  - csharp
  - aspnet-core
  - dependency-injection
  - software-architecture
  - dotnet
seoTitle: 'C# DI Lifetimes & Captive Dependency Trap Explained with Examples'
seoDescription: >-
  Understand ASP.NET Core DI lifetimes—Singleton, Scoped, Transient—and how to avoid the Captive Dependency Trap with code samples, diagrams, observability & best practices.
category: tech-stacks
---

## Q7 — DI Service Lifetimes — Singleton, Scoped, Transient and the Captive Dependency Trap

*Level: Mid-Level | Topic: ASP.NET Core Dependency Injection*

Dependency Injection (DI) is a cornerstone of modern ASP.NET Core applications, enabling loosely coupled code and easy testability. Understanding the three fundamental DI service lifetimes—Singleton, Scoped, and Transient—is critical to design robust services that work as expected under concurrent load and lifetime constraints.

Misusing lifetimes often leads to subtle, hard-to-diagnose runtime bugs, most notably the **Captive Dependency Trap**, a classic pitfall where a singleton inadvertently holds onto a scoped service causing leaked resources and corrupted state.

This article revisits these concepts with detailed explanations, rich examples, architecture diagrams, and production safety tips.

---

## The Three Lifetimes: Detailed Overview

### Singleton Lifetime

- **One instance per application process.**
- Instantiated once when first requested or during startup (if eagerly initialized).
- Shared across all requests and threads.
- Use cases: stateless services, caching providers, configuration readers.
- **Thread safety is mandatory** because a singleton can be accessed concurrently.
- Example: `IConfiguration`, logging service instances.

### Scoped Lifetime

- **One instance per scope; in web apps, per *HTTP request***.
- Acts like a unit-of-work boundary.
- Scoped services are created when a scope is started, disposed when it ends.
- Use cases: Entity Framework Core `DbContext`, transactional services, request-specific cache.
- Useful where you want object state tied to a single logical operation.

### Transient Lifetime

- **New instance created each time requested.**
- Lightweight, stateless services are best suited.
- Can flood the GC under heavy load if misused.
- Use cases: email sender, formatting helpers, lightweight utilities.
- Avoid heavy objects or resources with expensive lifetimes as transients.

---

## The Captive Dependency Trap Explained

When a *singleton* depends directly on a *scoped* service, the scoped service instance effectively becomes a singleton because the singleton’s reference lives for the app lifetime. This leads to:

- **Leaked scoped resources** such as database connections or file handles.
- **State corruption** because the scoped service’s state is shared across unrelated requests.
- **Disposal issues** where `Dispose`/`IAsyncDisposable` never runs because the scope is never completed.

This bug is hard to detect in small systems but causes major issues in production, such as:
- Connection pool exhaustion.
- Data conflicts.
- Unexpected side effects from stateful services.

### Visualizing the Issue

```mermaid
flowchart LR
    A[Singleton Service] -->|Captures| B[Scoped Service]
    B -->|Holds| C[DbContext or Resource]
    B -- "Expected per request" --> D[Request 1]
    B -- "Expected per request" --> E[Request 2]
    C -.->|"Never disposed"| F[Resource Leak / Stale State]

This shows a singleton capturing a scoped service reference that crosses request boundaries, leading to leaks.


Correctly Using Scoped Services in a Singleton

The right architectural pattern is to inject a factory or scope-creating service inside the singleton and create a scope/lifetime when you need the scoped services.

sequenceDiagram
    participant Caller as Client Code
    participant CacheSvc as CacheService (Singleton)
    participant ScopeFact as IServiceScopeFactory
    participant Scope as IServiceScope
    participant Repo as IOrderRepository (Scoped)

    Caller->>CacheSvc: Call RefreshAsync()
    CacheSvc->>ScopeFact: CreateAsyncScope()
    ScopeFact->>Scope: Returns new scope
    CacheSvc->>Scope: GetRequiredService<IOrderRepository>()
    Scope->>Repo: Instantiate scoped repository
    CacheSvc->>Repo: Query orders
    Repo-->>CacheSvc: Returns data
    CacheSvc-->>Caller: Returns refreshed data
    CacheSvc->>Scope: Dispose scope (Cleanup)

This sequence illustrates how CacheService creates a new DI scope each time it needs a scoped dependency, ensuring proper disposal.


Registration Patterns and Code Examples

Registration

// Registration of services with lifetimes
services.AddSingleton<IConfigProvider, AppConfigProvider>();  // Global singleton
services.AddScoped<IOrderRepository, EfOrderRepository>();    // One per request
services.AddTransient<IEmailSender, SmtpEmailSender>();       // Lightweight transient

WRONG Example: Captive Dependency Trap

// Singleton capturing scoped service - BAD
public class CacheService  // Singleton
{
    private readonly IOrderRepository _repo;  // Scoped service injected directly

    public CacheService(IOrderRepository repo) => _repo = repo;

    public async Task RefreshAsync()
    {
        var orders = await _repo.GetAllAsync();
        // Here, _repo is held for app lifetime, causing leaks
    }
}

Notice the direct injection of the scoped repository into a singleton, causing the scoped instance to live the full app lifetime.


CORRECT Example: Using IServiceScopeFactory

public class CacheService  // Singleton
{
    private readonly IServiceScopeFactory _scopeFactory;

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

    public async Task RefreshAsync()
    {
        // Create scope per operation
        await using var scope = _scopeFactory.CreateAsyncScope();
        var repo = scope.ServiceProvider.GetRequiredService<IOrderRepository>();

        var orders = await repo.GetAllAsync();

        // Scope disposed here, DbContext disposed properly
    }
}

This safe pattern creates a scope manually each operation needing scoped services, preventing resource leaks.


Comparing Service Lifetime Characteristics

LifetimeInstantiation FrequencyThread Safety Required?Typical Use CasesDisposal TimingCommon Pitfalls
SingletonOne per applicationYesConfiguration, logging, cachesDisposal at app shutdownCaptive dependency trap with scoped deps
ScopedOne per scope (web: per request)No (per scope)DbContext, unit of work, request dataScope disposal (end of request)Injecting into singletons directly
TransientEach injectionNoLightweight, stateless utilitiesDisposal when GC collects (or manual)Overuse causing GC pressure

Architecture - High-Level Diagram of DI Lifetimes in ASP.NET Core

flowchart LR
    subgraph App[Application Lifetime]
        S[Singleton Service] -->|Depends on| S2[Singleton Service 2]
    end

    subgraph Request1[HTTP Request 1 - Scoped Lifetime]
        SC1[Scoped Service] --> DB1[DbContext 1]
        SC1 --> S2
        SC1 --> T1[Transient Service 1]
    end

    subgraph Request2[HTTP Request 2 - Scoped Lifetime]
        SC2[Scoped Service] --> DB2[DbContext 2]
        SC2 --> S2
        SC2 --> T2[Transient Service 2]
    end

    S --> SC1
    S --> SC2

    style SC1 fill:#f9f,stroke:#333,stroke-width:2px
    style SC2 fill:#f9f,stroke:#333,stroke-width:2px

This diagram illustrates the relationship between Singleton, Scoped (per request), and Transient lifetimes in a typical ASP.NET Core web application.


Observability Recommendations

Monitoring and diagnosing lifetime and DI-related bugs require mindful logging, metrics, and tracing.

What to Log

  • Service creation and disposal: log when scoped and singleton services are created and disposed.
  • Scope lifetimes: log scope start and end times with unique identifiers.
  • Failures: log exceptions or failed resolutions from the DI container.
  • Scope validation warnings: captured by ASP.NET Core DI validation.

Example structured log entry in JSON (using Serilog for illustration):

{
  "Timestamp": "2024-06-01T14:32:00Z",
  "Level": "Information",
  "Message": "Created scope for HTTP request",
  "ScopeId": "123e4567-e89b-12d3-a456-426614174000",
  "Service": "IOrderRepository",
  "Action": "Instantiate",
  "ThreadId": 8
}

Key Metrics to Track (Based on RED and USE Models)

MetricTypePurpose
Request rateRED (Rate)Number of HTTP requests received per second
Error rateRED (Errors)Number of failed DI resolutions or scope errors
Request durationRED (Duration)Time taken to resolve requests
Service instance countUSE (Utilization)Number of active singleton and scoped instances
Garbage collection pause timeUSE (Saturation)High GC might indicate transient overuse

Distributed Tracing with OpenTelemetry

Add OpenTelemetry instrumentation to capture service lifetimes and scope propagation:

// Program.cs snippet: setup OpenTelemetry tracing with ASP.NET Core
builder.Services.AddOpenTelemetryTracing(tracerProviderBuilder =>
{
    tracerProviderBuilder
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddSource("MyApp.CacheService")
        .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("MyApp"))
        .AddConsoleExporter();
});

// Inside CacheService to create spans per scoped operation
public async Task RefreshAsync()
{
    using var activity = MyActivitySource.StartActivity("CacheService.RefreshAsync");
    await using var scope = _scopeFactory.CreateAsyncScope();
    var repo = scope.ServiceProvider.GetRequiredService<IOrderRepository>();
    var orders = await repo.GetAllAsync();
    activity?.SetTag("orders.count", orders.Count);
}

This snippet shows basic integration of OpenTelemetry for tracing the service and scoped lifetimes within a singleton operation.


SLI/SLO Table for DI Service Lifetimes

SLITarget (SLO)Alerting Threshold
% of successful DI resolutions≥ 99.9%Alert if < 99.5% over 5 minutes
Average service resolution time≤ 10 msAlert if > 100 ms for 5% of requests
Memory utilization for scoped objectsKeep GC pauses below 50 msAlert if GC pressure causes > 100 ms pauses
Scope validation warningsZero in productionAlert on any validation warning logs

Senior Insight Summary & Best Practices

  • Enable ValidateScopes = true and ValidateOnBuild = true in development to detect captive dependencies and registration errors early.
  • Avoid injecting scoped services into singletons directly.
  • When singleton requires scoped dependencies, use IServiceScopeFactory or a similar factory pattern to create discrete scopes.
  • Always design your services with lifetime boundaries in mind: think about disposal, concurrency, and when state should or should not be shared.
  • Utilize logging, metrics, and tracing for proactive detection of misuse and system load issues.
  • Refactor aggressively if you detect lifetime mismatches — they are often a symptom of design issues.

By mastering DI lifetimes and avoiding the Captive Dependency Trap, you build more stable, efficient, and scalable ASP.NET Core applications that behave predictably under load and complexity.

This knowledge is commonly tested in mid-level and senior C# interviews because it reflects deep understanding of .NET Core internals and software design.


Additional Resources


Appendix: Minimal & Realistic Code Examples

Minimal Example: Register and Resolve Services

var services = new ServiceCollection();

services.AddSingleton<IConfigProvider, AppConfigProvider>();
services.AddScoped<IOrderRepository, EfOrderRepository>();
services.AddTransient<IEmailSender, SmtpEmailSender>();

var provider = services.BuildServiceProvider(validateScopes: true);

using var scope = provider.CreateScope();
var repo = scope.ServiceProvider.GetRequiredService<IOrderRepository>();
// Use repo here

This minimal snippet shows how to register services and manually create a scope to resolve scoped services.


Realistic Example: Singleton using Scoped Service Safely

public interface IOrderRepository
{
    Task<List<Order>> GetAllAsync();
}

public class EfOrderRepository : IOrderRepository, IDisposable
{
    private readonly DbContext _context;

    public EfOrderRepository(DbContext context) => _context = context;

    public async Task<List<Order>> GetAllAsync() =>
        await _context.Set<Order>().ToListAsync();

    public void Dispose() => _context.Dispose();
}

public class CacheService  // Singleton
{
    private readonly IServiceScopeFactory _scopeFactory;

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

    public async Task RefreshAsync()
    {
        await using var scope = _scopeFactory.CreateAsyncScope();
        var repo = scope.ServiceProvider.GetRequiredService<IOrderRepository>();
        var orders = await repo.GetAllAsync();
        // Populate cache here with orders
    }
}

This realistic example illustrates correct management of a scoped repository inside a singleton cache service, including DbContext disposal.


Deep Internal Mechanics of ASP.NET Core DI Lifetimes and Scope Management

Understanding lifetimes superficially is not enough. Internally, the DI container in ASP.NET Core manages object creation and disposal via a carefully layered architecture. This section dissects how the container supports lifetimes, tracks scopes, and cleans up resources.

1. The Root IServiceProvider and Scopes

ASP.NET Core DI relies on IServiceProvider instances to manage service lifetimes. The key points:

  • There is one root IServiceProvider created on BuildServiceProvider() call. This is the application root scope.
  • Singleton services are created and cached in the root scope.
  • Each call to CreateScope() creates a child IServiceScope with its own IServiceProvider.
  • Scoped services are created once per scope and cached inside that scope’s IServiceProvider instance.
  • Transient services are created every time requested, with no caching or lifetime tracking.

2. How Services are Resolved

Services are resolved by the service provider calling factories (generated from ServiceDescriptors) with regard to the current scope.

flowchart TD
    RootSP[Root ServiceProvider]
    ScopeSP[IServiceScope ServiceProvider]
    RequestSvc[Resolve Service]
    Factory1[Factory: Singleton Service]
    Factory2[Factory: Scoped Service]
    Factory3[Factory: Transient Service]

    RequestSvc -->|Calls| RootSP
    RootSP -->|Serves Singleton| Factory1
    RootSP -->|Creates Scoped| ScopeSP
    ScopeSP -->|Serves Scoped| Factory2
    ScopeSP -->|Creates Transient| Factory3
  • The root provider caches and returns the singleton instance after first creation.
  • Each scope caches or creates scoped instances.
  • Transient services bypass caching and always create new instances.

3. Disposal Tracking

ASP.NET Core DI tracks IDisposable and IAsyncDisposable (from .NET Core 3.0+) services created within a scope.

  • When a scope is disposed, all disposable instances created in that scope are disposed in reverse order of creation.
  • Singleton disposables are disposed only when the root provider is disposed (i.e., on app shutdown).
  • Transients are never tracked for disposal by default — if you need disposal, transient services should be resolved from a scope.

4. What Goes Wrong in the Captive Dependency Trap?

In the captive dependency trap, a scoped dependency instance reference escapes scope because:

  • It is injected directly into a singleton constructor.
  • The singleton caches the reference for its entire lifetime (root scope).
  • The scoped service is created once, but expected to be one per request.
  • Disposal never happens because the scope is not actually created — injection happens at root.

This bypasses the entire scoped lifecycle, and scoped IServiceProvider caching/cleanup is skipped:

flowchart LR
    RootSP[Root ServiceProvider]
    Singleton[Singleton Service] -- holds --> ScopedInstance[Scoped Service instance]
    RootSP -- creates ScopedInstance once --> ScopedInstance
    Note1[Expected: Scoped per request] -- skipped --> ScopedInstance

This leads to uncontrolled resource retention, stale data, and concurrency errors.


Real-World Production Scenario: Diagnosing the Captive Dependency Trap

A complex, multi-tenant ASP.NET Core API suffers occasional timeouts and memory leaks around its caching service layer. The service caches user preferences but exhibits state mixups between tenant requests, causing customer data contamination.

Step 1: Symptom Analysis

  • High memory usage and slow response times after load increase.
  • DbContext usage spikes without proportional request traffic.
  • Inconsistent cache contents between requests.

Step 2: Hypothesis

A singleton service holding onto a scoped service, e.g., DbContext or repository, is causing the resource to stay alive and share data across tenants/requests.

Step 3: Verification by Code Inspection

Look for constructors in singleton class registering scoped services:

public class UserCacheService
{
    private readonly IUserPreferenceRepository _repo;  // Scoped service directly injected!

    public UserCacheService(IUserPreferenceRepository repo) => _repo = repo;
}

This is a clear captive dependency.

Step 4: Runtime Validation

Enable ValidateScopes in Startup or Program.cs:

services.BuildServiceProvider(new ServiceProviderOptions
{
    ValidateScopes = true // Detect captive deps during resolve
});

ASP.NET Core will throw a runtime exception like:

InvalidOperationException: Cannot consume scoped service 'IUserPreferenceRepository' from singleton 'UserCacheService'.

If ValidateScopes was off in production, this error is silent.

Step 5: Corrective Action

Refactor singleton to use IServiceScopeFactory:

public async Task RefreshUserCacheAsync()
{
    await using var scope = _scopeFactory.CreateAsyncScope();
    var repo = scope.ServiceProvider.GetRequiredService<IUserPreferenceRepository>();
    var prefs = await repo.GetPreferencesAsync();
    PopulateCache(prefs);
}

Step 6: Observability and Monitoring Post-fix

  • Add structured logs for scope creation.
  • Track disposal of DbContext/repositories.
  • Monitor GC pressure and connection pool saturation.

This end-to-end diagnosis and fix reduces memory leaks and data anomalies immediately.


Advanced Performance Considerations for DI Lifetimes

DI lifetimes have subtle effects on app performance and resource utilization, especially at scale.

1. Memory Overhead and Caching

  • Singletons keep their instance alive for app lifetime, so large stateful singletons can consume significant memory.
  • Scoped services tied to HTTP request lifetime free memory on request completion, aiding GC efficiency.
  • Incorrect lifetime can cause memory leaks—e.g., singleton holding transient or scoped with unmanaged resources.

2. Concurrency and Thread Safety

  • Singletons may be accessed simultaneously on multiple threads.
  • Any state field in a singleton must be protected with locks or be immutable.
  • Scoped instances are per-request, so no cross-thread concurrency issues assuming single-threaded request pipeline.
  • Transients should also be thread-safe if shared beyond scope.

3. Overhead of Scope Creation

  • Creating IServiceScope has a cost—time to instantiate services and track disposables.
  • Overuse in high-frequency code (e.g., per database call instead of per request or per logical operation) can add latency.
  • Balance scope lifespan to avoid unnecessary scope creation yet keep resource isolation.

4. Garbage Collection Impact

  • Transient-heavy DI patterns cause many short-lived objects quickly collected by Gen 0 GC.
  • If discarding disposables anytime or not disposing scoped instances properly, Gen 2 heap will accumulate.
  • Use profiling tools (dotnet-counters, dotnet-trace, PerfView) to identify GC patterns linked to DI lifetime use.

5. Compiled and Cached Factories

  • ASP.NET Core DI generates compiled factories for service creation.
  • These factories improve performance over reflection activators.
  • Lifetime management is embedded in factory-generated code, optimised for singleton cache or scoped cache.
  • Custom factories or proxy patterns (like interceptors) may impact performance; measure and balance.

Observability: Structured Logging, Metrics, and Distributed Tracing for DI Lifetimes

Deep insight requires observability baked into DI usage, especially around scopes and singleton usage.

What to Log

  • Scope lifecycle events: When scopes are created and disposed.
  • Service instance creation: Class name, lifetime, thread ID.
  • Disposal events: When services implementing IDisposable or IAsyncDisposable are disposed.
  • Failures: DI resolution failures or scoped service usage outside scope.
  • Singleton-scoped dependency warnings: Special warning logs if singleton tries to hold scoped.

Example Serilog structured log:

{
  "Timestamp": "2024-06-01T14:32:00Z",
  "Level": "Information",
  "EventId": "ScopeCreated",
  "ScopeId": "31f7662a-2440-4c56-b4b3-1f477b3ac1a1",
  "ServiceName": "IOrderRepository",
  "Operation": "Resolve",
  "ThreadId": 12,
  "RequestId": "19abf942-5a33-4f82-88e1-7e073ab6f5db"
}

Key Metrics

MetricDescriptionCollection Source
Service resolution success rate% of successful DI service resolvesApplication telemetry
Scope creation rateNumber of scopes created per secondMiddleware or custom hooks
Scoped service disposal latencyTime between scope disposal and resource cleanupCustom instrumentation
Transient service churn rateApproximate number of transient instances created per secondProfiling, app telemetry
Memory usage by DI instancesHeap memory size consumed by DI instancesRuntime telemetry, GC events

Distributed Tracing

  • Span creation aligned with service scope creation.
  • Tagging spans with service.lifetime (singleton, scoped, transient).
  • Propagate context into scoped operations manually if you create scopes outside of HTTP context.
  • Example with OpenTelemetry (System.Diagnostics.Activity):
public async Task SomeSingletonOperation()
{
    using var activity = MyActivitySource.StartActivity("SingletonOperation");
    await using var scope = _scopeFactory.CreateAsyncScope();
    activity?.SetTag("service.lifetime", "scoped");

    var repo = scope.ServiceProvider.GetRequiredService<IOrderRepository>();
    var data = await repo.GetAllAsync();

    activity?.SetTag("result.count", data.Count);
}

SLI/SLO Table (Refined)

SLISLO TargetAlert Condition
DI Resolution Success Rate≥ 99.95%Trigger if below 99.9% for 10 min
Scoped Service Disposal Latency< 100 ms on averageAlert if > 500 ms on 1% of scopes
Memory Used by Scoped InstancesWithin expected baselineAlert on 20%+ increase week over week
Garbage Collection Pause Time< 50 ms Gen 2 pausesAlert if frequent large pauses
Validation ErrorsNone in productionImmediate alert on any occurrence

Checklist for Selecting Appropriate DI Lifetimes and Avoiding Captive Dependency Trap

QuestionConsiderationsRecommended Action
Does the service hold per-request state?If yes, it should be scoped.Register as scoped.
Is the service stateless or global shared?Use singleton.Register as singleton.
Is the service heavyweight to create repeatedly?Prefer scoped over transient.Use scoped or singleton as fits.
Do higher lifetime services depend on lower lifetime ones?Avoid injecting scoped service into singleton directly.Use factory or create a scope manually.
Are disposable resources involved?Ensure service gets disposed appropriately.Match lifetime and dispose accordingly.
Is the service thread safe for singleton?Ensure immutable state or proper synchronization.Add locking or switch lifetime.
Will the service be resolved outside an HTTP request?May need transient or manual scope management.Avoid scoped dependency in singleton.

Use this checklist as a design step before adding services to DI.


Common Edge Cases and Failure Modes

1. Scoped Services in Background Hosted Services (Singleton)

Many developers inject scoped services into hosted background workers (which are singleton). This leads to the captive dependency.

Solution: Use a scope factory inside the hosted service to create a scope per background operation.

public class Worker : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;
    public Worker(IServiceScopeFactory scopeFactory) => _scopeFactory = scopeFactory;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await using var scope = _scopeFactory.CreateAsyncScope();
            var scopedService = scope.ServiceProvider.GetRequiredService<IScopedDependency>();
            await scopedService.DoWorkAsync();
            await Task.Delay(1000, stoppingToken);
        }
    }
}

2. Transient Services Holding Disposable Resources

Transient services are not tracked for disposal — resolving them in singleton scope means leaks unless disposed manually.

Solution: Either:

  • Make the service scoped (usually better).
  • Dispose the transient manually immediately after use.

3. Detecting Captive Dependency at Runtime

Without ValidateScopes enabled, no error is thrown. Production systems with ValidateScopes=false are vulnerable.

Mitigation:

  • Enable ValidateScopes during development.
  • Use Static Code Analysis tools and dependency graph exams.
  • Unit/integration tests to cover lifetime edge cases.

4. Circular Dependency Can Confuse Lifetimes

Circular dependency chains involving both scoped and singleton services complicate the container’s lifetime management and often cause runtime exceptions.

Resolution:

  • Refactor design to avoid cycles.
  • Use factories or delegate injections.
  • Use explicit scope factories to demarcate boundaries.

By comprehensively understanding the internal lifecycle management of ASP.NET Core DI, diagnosing complex production issues becomes systematic. Careful design of lifetimes combined with observability ensures sustainable and high-performance .NET services.