Reading the docs :
When the app is running in the Development environment, the default service provider performs checks to verify that:
- Scoped services aren't directly or indirectly resolved from the root service provider.
- Scoped services aren't directly or indirectly injected into singletons
This means that I shouldn't inject Scoped services into a singleton service.
Based on the fact that transient services creates an instance each time they're requested, VS scoped services which are single instances throughout the request's lifecycle :
Question:
Why does the DI only validate scoped services and not also transient services?
Use Transient lifetime for the lightweight service with little or no state. Scoped services service is the better option when you want to maintain state within a request. Singletons are created only once and not destroyed until the end of the Application. Any memory leaks in these services will build up over time.
Scoped is a single instance for the duration of the scoped request, which means per HTTP request in ASP.NET. Transient is a single instance per code request.
With a transient service, a new instance is provided every time an instance is requested whether it is in the scope of same http request or across different http requests. With a scoped service we get the same instance within the scope of a given http request but a new instance across different http requests.
It's dangerous to resolve a scoped service from a singleton. It may cause the service to have incorrect state when processing subsequent requests.
From the Docs the above describes why they do this check. To understand this better I started reading about the various lifetimes more being an autofac guy myself to understand the .net core flavor of registrations.
startup.cs
) Generally you would us the singleton pattern to maintain perhaps some sort state in memory for your application lifetime etc, there are many use cases but the important thing to understand that the constructor of your singleton class (where you inject your dependencies) will run once and only once for your entire application lifetime.
You could imagine that injecting a scoped or transient service into singleton while baring the above in mind will lead to some ... unexpected results , you are expecting your service to adhere to its specific life time but in actual fact its really just the same instance every time due to the nature of the singleton.
To answer your question using my understanding : A transient injected into a singleton (while inherently not correct) will still function fine as its lifetime is short and runs of little risk of breaking state whereas scoped guarantees a lifetime across a single request (think some sort of request caching as an example), there is no way that scoped can honor that lifetime while being injected into a singleton.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With