ASP.NET Core DI captive dependency
What is a captive dependency in ASP.NET Core DI, and how do you detect/fix it?
Answers use simple, clear English.
Quick interview answer
A longer-lived service (Singleton) depends on a shorter-lived one (Scoped DbContext) — the scoped instance is captured and reused across requests causing bugs/threading issues. Detect with ValidateScopes/ValidateOnBuild in Development. Fix: change lifetimes, use IServiceScopeFactory inside singleton, or make both scoped.
Detailed answer
A longer-lived service (Singleton) depends on a shorter-lived one (Scoped DbContext) — the scoped instance is captured and reused across requests causing bugs/threading issues. Detect with ValidateScopes/ValidateOnBuild in Development. Fix: change lifetimes, use IServiceScopeFactory inside singleton, or make both scoped.
Real example & use case
Singleton CacheWarmer incorrectly injecting AppDbContext — switch to IServiceScopeFactory.CreateScope().
Pros & cons
Pros of validation: fail fast. Cons: must understand lifetimes deeply.