Service lifetimes transient vs scoped vs singleton [closed]

蓝咒 提交于 2020-01-01 06:26:43

问题


I found an article on

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1

and it explains a asp.net core DI and service lifetime.

Article mentions following lifetimes:

  • transient
  • scoped
  • singleton

I am trying to find a real world example or at least a better explanation on when to use each lifetime.


回答1:


3 examples:

Singletons - These may exist for the entire application wide configuration setting, for example a game manager that keeps track of players progress throughout the game.

Scoped - entity framework contexts are recommended to be scoped so that you can reuse the connection properties.

Transient - entity framework contexts can not be shared by 2 threads, so if you wanted to do any asynchronous work. You would use a transient so that a new instance of the context is created for every component. Otherwise you would have to wait for the scoped component to finish before it moves onto the next.



来源:https://stackoverflow.com/questions/52774336/service-lifetimes-transient-vs-scoped-vs-singleton

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