Advertisement
Advanced C#, Dependency Injection & IoC Principles

What causes a 'captive dependency' bug, and how does ASP.NET Core's DI container detect and prevent it?

Short answer

A captive dependency occurs when a longer-lived service (like Singleton) injects a shorter-lived one (like Scoped) — the Scoped instance gets 'captured' and effectively lives as long as the Singleton, defeating its intended per-request lifecycle and potentially causing stale…

Save C# mock interview
Advertisement
AModel answer
A captive dependency occurs when a longer-lived service (like Singleton) injects a shorter-lived one (like Scoped) — the Scoped instance gets 'captured' and effectively lives as long as the Singleton, defeating its intended per-request lifecycle and potentially causing stale data or thread-safety issues; ASP.NET Core's DI container detects this specific misconfiguration and throws an exception at service resolution time by default (with scope validation enabled).
builder.Services.AddSingleton<ICacheService, CacheService>();
builder.Services.AddScoped<IDbContext, AppDbContext>();

public class CacheService : ICacheService {
  public CacheService(IDbContext db) { } // Error at startup: captive dependency detected!
}
Real-world example
Debugging a subtle production bug where a database context was unexpectedly shared and stale across multiple unrelated requests.
Likely follow-ups
  • How would you correctly restructure a Singleton that genuinely needs access to Scoped services on demand, using IServiceScopeFactory?
Related topics