There is a problem of not correctly configured DI containers named Captive Dependency by Mark Seemann. It's obviously, for example, when a "PerCall" dependency is injected into a "Singleton" one. But what about a scenario when "Transient" is injected into "Singleton"? It’s not so obvious to me why I shouldn’t do that especial for some scenarios like a timer registered as transient injected into a singleton service and lives there forever.
There is Lifestyle Mismatches diagnostic warning in SimpleInjector DI container. The description says:
it is safe for a transient component to depend on a singleton, but not the other way around
Why is it bad? A good example of bad things in this case will be extremely useful. Is there any limitation when it "always" bad or some scenarios can be allowed (see my example above)?
It's not safe because your transient instance will be forever inside singleton.
Example: you can inject singleton into some another class instance. In that case you will indirectly inject transient instance too. So you can face with thread-safety problems for instance.
If you register class as a singleton you consider it as a thread-safe because you can use the same instance concurrently in few threads. If you register class as transient most likely it's a lightweight and not thread-safe class. That's why you registered it as transient not as singleton, right? And that's why you see warnings: it's not safe to use transient objects concurrently. In asp.net core embedded IoC you will face runtime exception in such case.
Imagine: your transient class creates
SqlConnectioninside and keeps it opened during its lifetime and allows to use it without synchronization. And that's OK because it's considered to be alive for a short period of time in one thread. Then you inject it into singleton and then you use this singleton in each request.