问题
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