wasAsked.

What is a captive dependency?

Routeware · Role not specified · technical

Published

Year not specified · .NET

Community answers

Posted by wasAsked editorial collection

A captive dependency happens when a service with a longer lifetime holds on to a service that should have a shorter lifetime. The shorter-lived service becomes "captive" and lives as long as its consumer. The classic case in ASP.NET Core: builder.Services.AddDbContext<AppDbContext>(); // scoped: one per request builder.Services.AddSingleton<PriceCache>(); // singleton public class PriceCache(AppDbContext db) { ... } // singleton captures a scoped DbContext Consequences: - The same DbContext is used by every request for the life of the app. - DbContext is not thread-safe, so concurrent requests throw "A second operation was started on this context instance". - Its change tracker keeps growing (memory leak) and returns stale tracked entities. - Request-specific data (current user, tenant) from the first request leaks into later ones. Lifetime rule: a service may depend only on services with the same or a longer lifetime. - Singleton can depend on singleton. - Scoped can depend on scoped or singleton. - Transient can depend on anything, but a transient captured by a singleton also lives forever. Detection: - ASP.NET Core enables scope validation in the Development environment, throwing "Cannot consume scoped service 'AppDbContext' from singleton 'PriceCache'". - Enable it everywhere during tests: builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; }); Fixes: 1. Change the consumer's lifetime to scoped if it does not need to be a singleton. 2. Inject IServiceScopeFactory and create a scope for each unit of work: using var scope = scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService<AppDbContext>(); 3. For EF Core, inject IDbContextFactory<AppDbContext> and create short-lived contexts. 4. Pass the data (not the service) into the singleton. Captive dependencies are a common interview question because they cause bugs that appear only under concurrent load in production.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics