What is the 'captive dependency' problem, and how does ASP.NET Core's DI container help catch it automatically?
Short answer
A captive dependency occurs when a longer-lived service (Singleton) depends on a shorter-lived service (Scoped), effectively 'capturing' that shorter-lived instance for the Singleton's entire lifetime -- potentially causing serious bugs like a captured DbContext being reused…
Advertisement
AModel answer
A captive dependency occurs when a longer-lived service (Singleton) depends on a shorter-lived service (Scoped), effectively 'capturing' that shorter-lived instance for the Singleton's entire lifetime -- potentially causing serious bugs like a captured DbContext being reused indefinitely across unrelated requests. ASP.NET Core's DI container detects this by default (in Development, via scope validation) and throws an InvalidOperationException at service resolution time rather than allowing the bug to silently occur.
builder.Services.AddSingleton<INotificationService, NotificationService>();
builder.Services.AddScoped<AppDbContext>();
// NotificationService depending on AppDbContext throws at resolution:
// "Cannot consume scoped service 'AppDbContext' from singleton 'INotificationService'"
// Fix: inject IServiceScopeFactory into the Singleton and create scopes on demand insteadReal-world example
A subtle production bug where all users started seeing the same cached database results was traced to a captive dependency -- a Singleton service had captured a Scoped DbContext, which the built-in scope validation would have caught immediately during local development.
Likely follow-ups
- How do you fix a captive dependency once identified?
- Why is scope validation enabled by default in Development but not always in Production?
Related topics