"Captive DI" refers to a captive dependency: a dependency that is held captive by a consumer with a longer lifetime than its own, so it lives much longer than intended. Example: services.AddScoped<IUserContext, HttpUserContext>(); // per request: knows the current user services.AddSingleton<AuditService>(); // one for the whole app public class AuditService(IUserContext userContext) { ... } AuditService is created once, with the IUserContext of the first request. Every later request writes audit records with the first user's identity — a serious data-integrity and security bug. With a scoped DbContext the symptoms are concurrency exceptions, memory growth and stale data. Why it happens: the container resolves constructor dependencies only when it creates the consumer. A singleton is created once, so its dependencies are resolved once. Lifetime compatibility: - Singleton may depend on: singleton only. - Scoped may depend on: scoped and singleton. - Transient may depend on: anything, but beware transient dependencies of singletons, which also become effectively singletons. How .NET protects you: - In the Development environment, ASP.NET Core validates scopes and throws InvalidOperationException: "Cannot consume scoped service from singleton". - Turn on ValidateScopes and ValidateOnBuild in all environments during testing to catch it early. How to fix it: 1. Make the consumer scoped if it does not truly need to be a singleton. 2. Inject IServiceScopeFactory and create a scope when the work runs (common in BackgroundService). 3. Use factories designed for this, such as IDbContextFactory<T> or IHttpClientFactory. 4. Pass request data as method parameters instead of injecting request-scoped services into long-lived objects.
Ravindra Wadile · · 0 likes