📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is a captive dependency, and how does ValidateScopes help you catch it?

Junior Theory Beginner captive-dependency dbcontext dependency-injection service-lifetimes validate-scopes

🎯 Key points

  • Shorter-lived dependency held by a longer-lived consumer
  • Scoped DbContext in a singleton is the classic case
  • In production: shared across threads (EF concurrency exceptions), stale identity-map data, never disposed, change tracker grows
  • ValidateScopes throws on singleton→scoped and scoped-from-root
  • The host turns it on only in Development by default; enabling it everywhere costs a little per-resolution checking and catches the bug before it ships
  • Combine with ValidateOnBuild so the check runs at start-up for every registration
  • Fix: align lifetimes, or IDbContextFactory<T> / IServiceScopeFactory per unit of work

⏱ 30-second answer

A captive dependency is a shorter-lived service captured by a longer-lived one, usually a scoped DbContext held by a singleton. The scoped instance stops being per-request: in production it is shared across threads (EF's "second operation" exceptions), serves stale data from its identity map, keeps growing its change tracker and is never disposed.

ValidateScopes = true makes the provider throw when a singleton's graph contains a scoped service or a scoped service is resolved from the root. The host enables it only in Development by default; turn it on everywhere with builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; }). The cost is a small check on resolution and a one-off graph walk at start-up, far cheaper than the outage. Fix by aligning lifetimes, or creating per-operation instances with IDbContextFactory<T> or IServiceScopeFactory.

🔍 What the interviewer is checking

Checks they can explain the failure mode and the guard rail

↩ Usually asked after

More in Service Lifetimes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me