Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service lifetimes transient vs scoped vs singleton [closed]

I found an article on

https://learn.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.

like image 795
mko Avatar asked Dec 13 '22 14:12

mko


1 Answers

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.

like image 105
Hawkzey Avatar answered Dec 16 '22 05:12

Hawkzey