DI Singleton instance vs Transient instance

泄露秘密 提交于 2019-12-13 18:35:35

问题


Several years ago IoC performance guidelines stated IoC containers should be used to resolve only long-lived instances (singletons basically), whereas transient type objects should be created using a singleton factory (held by the container).

I am reading now about ASP.NET Core, and several examples I have seen use Transient lifetime for their injected objects. Has something changed where transient is now the preferred method for services that provide static methods (and are stateless)?


回答1:


The notion of "long-lived instances" does not say anything about their lifetime or lifestyle per see, but rather that from perspective of the consumer, there is only one instance of them. They are stateless.

In other words, "long-lived instances" refers to services or dependencies, while "short-lived instances" refers to data-centric objects, such as entities, DTOs, messages and view models.

Those services are created and managed by your Composition Root (typically, but not nessicarily your DI Container), while data-centric objects are managed directly by application code. In other words, those "long-lived objects" are 'newed' up by the Composition Root, while "short-lived objects" are newed up by application code itself.

Those data-centric objects are volatile, they typically only live for the duration of the request (or even shorter), although they might be cached and live for as long as the application lives.

Dependencies can as well live for a short duration, but typically for the duration of a request.




回答2:


Nothing has changed.

I am not sure where you read that, but do note that a service cannot have a lifetime shorter than the services that depend on it. So, if you are injecting services into a singleton then you have the right idea - in that case you may need a factory in order to properly release the instance.

However, since ASP.NET Core resolves the controller instance on every request, injecting a transient dependency is fine as it will go out of scope when the controller is destroyed.



来源:https://stackoverflow.com/questions/48287571/di-singleton-instance-vs-transient-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!