Search code examples
asp.net-coredependency-injectionsingletontransientscoped

When to use following Transient, scoped and singleton


I read some articles about this and I get to know how to use Transient, Scoped, and Singleton but I am confused when to use one of these.

What I am understood:

Singleton: In situation when you need to store number of employees then you can create singleton cause every time you create new employee then it will increment the number so in that situation you need singleton.

Scoped: For example you are playing game in which number of life is 5 and then you need to decrease the number when player's game over. And in every new time you need new instance because every new time you need number of life is 5.

Transient: when to use Transient??

Please correct me if I am wrong. And give the better example of all of them if possible.


Solution

  • As far as I know, the Singleton is normally used for a global single instance. For example, you will have an image store service you could have a service to load images from a given location and keeps them in memory for future use.

    A scoped lifetime indicates that services are created once per client request. Normally we will use this for sql connection. It means it will create and dispose the sql connection per request.

    A transient lifetime services are created each time they're requested from the service container. For example, during one request you use httpclient service to call other web api request multiple times, but the web api endpoint is different. At that time you will register the httpclient service as transient. That means each time when you call the httpclient service it will create a new httpclient to send the request not used the same one .