7

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.

mko
  • 6,638
  • 12
  • 67
  • 118
  • 4
    We use Autofac's equivalent of "Scoped" for our user context object. We cache any permissions check results here so that we can reduce load on the database. The life of the user context object is the same as the life of the web request. We use "Singleton" for special factory services, since they live for the life of the application, and we use "Transient" for the things that the factories produce, services that shouldn't live for the life of the application, etc. – ProgrammingLlama Oct 12 '18 at 07:36
  • 3
    transient - stores no state; scoped - stores state for the lifetime of the request; singleton - stores state for the lifetime of the application – qujck Oct 12 '18 at 08:35
  • Duplicate: https://stackoverflow.com/questions/30681477/why-would-one-use-a-third-party-di-container-over-the-built-in-asp-net-core-di-c – Steven Oct 12 '18 at 09:00

1 Answers1

16

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.

maccettura
  • 10,514
  • 3
  • 28
  • 35
Hawkzey
  • 1,088
  • 1
  • 11
  • 21
  • Correct answer. You could add some information relative to captive dependencies traps. – xlecoustillier Oct 12 '18 at 08:43
  • Does this mean that Transient is the only lifetime which does not block during an async call? – TomDane Oct 17 '19 at 18:57
  • 1
    @TomDane out of the 3 scopes above you are indeed correct, a singleton could potentially be created multiple times if it was used in a threaded situation, a scoped lifecycle is designed to be used in a single scope, e.g. a single web request. so there is no need to multi thread in these scenarios. – Hawkzey Jan 28 '21 at 15:57