Back to Browse

Captive Dependency: Scoped in Singleton Services | ASP.NET Core DI #47

82 views
May 5, 2026
3:29

Learn about the captive dependency problem when injecting scoped services into singleton services in ASP.NET Core dependency injection and how to properly resolve scoped dependencies in . NET 10. Injecting a scoped service into a singleton is one of the most dangerous DI anti-patterns. The scoped service becomes captured by the singleton and lives for the entire application lifetime instead of being recreated per scope or request. This causes severe problems. Scoped services like DbContext are designed to live for a single request. When captured by a singleton, the same DbContext instance is reused across all requests, causing data corruption, concurrency issues, and connection leaks. ASP.NET Core's dependency injection container validates service lifetimes in development mode and throws exceptions when it detects scoped services injected into singletons. This validation prevents bugs before they reach production. The most common mistake is injecting DbContext or repositories into singleton background services or hosted services. This will cause exceptions at runtime. The correct solution is to inject IServiceScopeFactory into your singleton. When you need the scoped service, create a scope using CreateScope, resolve the scoped service from that scope, use it, and dispose the scope when done. This pattern ensures scoped services have the proper lifetime and are disposed correctly. Each operation gets a fresh scoped service instance with its own scope. Never try to bypass lifetime validation by changing service registrations. The validation exists to protect you from serious bugs. Follow the proper patterns instead. 🎓 Full Course Playlist: https://www.youtube.com/watch?v=OlRBdXaQm2M&list=PLaFzfwmPR7_KtNJZt9pn8RtDAA-Muk4ql ⭐ Join the Membership: https://www.youtube.com/channel/UC2Us1KkV7BMm5Rp6tV6tTxg/join 👍 Like if this saves you from bugs | 💬 Hit this error before? Share your story | 🔔 Subscribe for DI best practices #aspnetcore #captivedependency #dependencyinjection #dotnet10 #singletonservices #scopedservices #dbcontext #csharp

Download

0 formats

No download links available.

Captive Dependency: Scoped in Singleton Services | ASP.NET Core DI #47 | NatokHD