Sunday 31 January 2021

Part 18: DI services (Singleton, Transient and Scoped)

#10 minutes of reading

 

I’m using same sample created for DI article (part 17). Dependency injection provides three ways to register service and based on the selected way life of service decide. 

DI provide below three types

        1.       Singleton

        2.       Scoped

        3.       Transient

Singleton, Scoped, and Transient are three different ways in Asp.Net Core which helps to configure service with object lifetime, it means Singleton, Scoped, and Transient are used to decide how long object available or life of an service(DI configured service). Let’s understand with an example below.

 

Singleton: Object created only once and throughout application that same object is reused. This is same concept from Singleton design pattern. Let’s understand with an example.


 

Update create view of student controller

Add below highlighted line in create view of student controller.

Run application and you observe each time you add employee, it shows employee count increment  by 1 correctly.

Each time I click on create; count will increase. Count is nothing but total number of employees and when I click on create in background, I’m adding new employee to existing object and object persist throughout the application in singleton and return updated count of total number of employees.

 

 

Scoped: In this type, new object gets created for every pair of http request. Let’s move to visual studio and check how it works.

Open Startup file and modify service type to scoped shown below.

Run application and check in browser.

First time count is 2, as 2 records already available in list object. Click on create the count will increase 3 again click on create but this time count is 3. Whenever you create http pair of new requests it creates new object of type service StudentRepository. No matter how many times click on Create button but count always three after click on Create button.

Transient: Object gets created each time service gets called. Lets check in visual studio and modify service type to Transient in ConfigureServices method of startup file shown below.

Run application and check in browser.

No matter how many times click on create button but count should be 2 only as transient create new object each time we request.


Previous                                                                                                                                                Next

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home