ARJUN PATEL
ARJUN PATEL

Reputation: 117

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.

Upvotes: 7

Views: 27383

Answers (2)

user11137380
user11137380

Reputation: 31

Note, Microsoft provides the recommendations here and here.

When designing services for dependency injection:

  • Avoid stateful, static classes and members. Avoid creating global state by designing apps to use singleton services instead.
  • Avoid direct instantiation of dependent classes within services. Direct instantiation couples the code to a particular implementation.
  • Make services small, well-factored, and easily tested.

Upvotes: 2

Brando Zhang
Brando Zhang

Reputation: 27962

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 .

Upvotes: 21

Related Questions