ASP.NET Core Interview Question #59

What is a captive dependency?

Dependency Injection & Services Junior Beginner

Quick Interview Answer

A captive dependency occurs when a longer-lived service holds a dependency with a shorter lifetime, most commonly when a Singleton directly depends on a Scoped service.

Detailed Explanation

A captive dependency occurs when a longer-lived service holds a dependency with a shorter lifetime, most commonly when a Singleton directly depends on a Scoped service.

The scoped instance can then be retained far beyond its intended scope. With DbContext, this can cause concurrency problems, stale tracking state, resource lifetime issues, and incorrect behavior across requests.

The preferred solution is to redesign the lifetimes. If a singleton legitimately needs to perform scoped work, it can create a new scope for each operation using IServiceScopeFactory.

Code Example

public class BackgroundProcessor
{
    private readonly IServiceScopeFactory _scopeFactory;

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

    public async Task ProcessAsync()
    {
        using var scope = _scopeFactory.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();

        // Perform scoped work here.
    }
}