Alireza Farokhi
3 min readMay 18, 2022

Difference Between Singleton, Scoped, Transient Lifetime In Asp.net core

When we register a service, we must specify the type of lifetime. Asp.net core used this to know how to treat and do when a service is requested.

I’m going to explain this by example. You can download source code from this Repository :https://github.com/ARFarokhi/ServiceLifetime.

for the purpose of demonstrating lifetime and dependency injection, ids are generated in id-generator’s constructors .I’ve just injected “OrderService” in “OrderController” ,and in “CreateOrder” action get Ids from both and compare them.

after downloading source code run it by press F5 in visual studio or open command prompt then go to project directory and use “dotnet run” command and call “/api/orders” api

Singleton:

These services are created once and when you request (call or use or refer) these services, the same instance is used. this means there is no new instance of service, and same instance is used everywhere in the application.

first call

second call

as you can see all ids are the same. this means id-generator is instantiated just once.

Transient:

These services are created every time that service is requested. imagine you inject OrderService into OrderController and you inject IdGeneratorService in both. When OrderController receive the request, an IdGeneratorService instance is created and use in OrderController and another is created and use in OrderService (2 instances created for a request)

first call

second call

as you can see all ids are different. this means id-generator is instantiated every time is used(as mentioned above id is generated in constructor)

Scope:

These services are created only once per each request (scope), and be reuse multiple times within the request.to explain better, imagine you inject OrderService into OrderController and we inject IdGeneratorService in both. When OrderController receive request, an IdGeneratorService instance is created and use in controller and same is use in OrderService. this hierarchy can continue if there is another service inside OrderService.

first call

second call

as you can see ids in each request are same but different from each other. this means id-generator is instantiated per scope.

Services life time and dependency injection guide:

Singleton: can be injected in Singleton, Transient and Scope services

Scope: can be injected in Transient and Scope services

Transient: can be injected in Transient services

linked in:

https://www.linkedin.com/in/alirezafarokhi/