Injecting Transient into Singleton - Captive Dependency Problem | DI Tutorial #46
Learn about the captive dependency problem when injecting transient services into singleton services in ASP.NET Core dependency injection and how to avoid this common mistake in . NET 10. Injecting a transient service into a singleton creates a captive dependency anti-pattern. The transient service becomes captured by the singleton and lives for the entire application lifetime instead of being created fresh each time. This defeats the purpose of transient lifetime. Transient services are supposed to be created new for each resolution, but when injected into a singleton constructor, they become effectively singleton themselves. This can cause serious problems including stale data, memory leaks, incorrect state management, and unpredictable behavior across requests. If the transient service holds state or resources meant to be short-lived, they persist for the application lifetime. ASP.NET Core can detect this problem in development mode and will log warnings about captive dependencies. Always pay attention to these warnings. The solution is to NOT inject transients into singleton constructors. Instead, use IServiceProvider or IServiceScopeFactory to resolve transient services on-demand when needed. Create a scope, resolve the transient, use it, and dispose the scope. Alternatively, reconsider your service lifetimes. If a singleton truly needs a dependency, that dependency should probably also be a singleton. Design your dependency graph to avoid mixing incompatible lifetimes. This is one of the most important rules in dependency injection: shorter lifetimes should never be injected into longer lifetimes. 🎓 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 captive dependency is clear | 💬 Caught this bug before? Share below | 🔔 Subscribe for DI best practices #aspnetcore #captivedependency #dependencyinjection #dotnet10 #singletonservices #transientservices #antipattern #csharp
Download
0 formatsNo download links available.