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?
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.