Understanding Service Lifetimes in .Net Core

Understanding Service Lifetimes in .Net Core

04 Jun 2024
Beginner
605 Views
7 min read
Learn via Video Course & by Doing Hands-on Labs

.NET Course

Service Lifetimes in .Net Core

ASP.NET Core allows us to specify the service lifetimes for registered services. The service instance gets disposed of automatically based on a specified lifetime. When a service requests another service via DI, knowing whether it receives the new instance or an existing instance is very important. Hence correctly specifying the lifetime while registering the service is of utmost importance. 

In this .NET Core tutorial, we will explore the types of Service lifetimes for dependency injection along with illustrations. Also, consider learning the ASP.NET Core Course for a better understanding and implementation of the .NET concepts. 

Top 50 .NET Core Interview Questions and Answers 2024

What are service lifetimes in .Net Core?

There are 3 different types of service lifetimes for dependency injection.

  • 1. Singleton Service
  • 2. Transient Service
  • 3. Scoped Service

What are service lifetimes?

1. Singleton

ASP.net core will create and share a single instance of the service through the application life. The service can be added as a singleton using the AddSingleton method of IServiceCollection. ASP.Net core creates a service instance at the time of registration and subsequent requests use this service instance. Here, we do not require implementing a singleton design pattern and single instance maintained by the ASP.net core itself.

public void ConfigureServices(IServiceCollection services)
{
 ….
 …
 services.AddSingleton<IHelloWorldService, HelloWorldService>();
 ….
 …
}

Singleton Example

//Step 1: Create the required service    
public interface IFirstSingletonService  
{  
  string HelloWorld();  
}  
   
public class FirstSingletonService: IFirstSingletonService  
{  
 public string ShowMessage()  
 {  
   return "Welcome to scholarhat" Singleton";  
 }  
}  
  
//Step 2: Add above created service to Service container as below    
public void ConfigureServices(IServiceCollection services)  
{  
 // .. other code  
 services.AddSingleton();  
 //.. other code  
}  
  
//Step 3: Use above created service as a dependency in the specific or required controller    
public class HomeController: Controller  
{  
 IFirstSingletonService _firstSingletonService;  
 public HomeController(IFirstSingletonService myFirstSingletonService)  
 {  
   _firstSingletonService = firstSingletonService;  
 }  
}  
    

2. Transient

ASP.net core will create and share an instance of the service every time to the application when we ask for it. The service can be added as Transient using the AddTransient method of IServiceCollection. This lifetime can be used in stateless service. It is a way to add lightweight service.

In other words, the transient service will be created every time as soon as it gets the request for the creation.

public void ConfigureServices(IServiceCollection services)
{
 ….
 …
 services.AddTransient<IHelloWorldService, HelloWorldService>();
 ….
 …
}

Transient Example

// Step 1: Create the required service    
public interface IFirstTransientService  
{  
  string HelloWorld();  
}  
   
public class FirstTransientService: IFirstTransientService  
{  
 public string ShowMessage()  
 {  
   return "Welcome to scholarhat Transient";  
 }  
}  
  
// Step 2: Add above created service to Service container as below   
public void ConfigureServices(IServiceCollection services)  
{  
 // .. other code  
 services.AddTransient();  
 //.. other code  
}  
  
//Step 3: Use above created service as a dependency in the specific or required controller    
public class HomeController: Controller  
{  
 IFirstTransientService _firstTransientService;  
 public HomeController(IFirstTransientService firstTransientService)  
 {  
   _firstTransientService = firstTransientService;  
 }  
}     

3. Scoped

ASP.net core will create and share an instance of the service per request to the application. It means that a single instance of service is available per request. It will create a new instance in a new request. The service can be added as scoped using the AddScoped method of IServiceCollection. We need to take care while the service is registered via Scoped in middleware and inject the service in the Invoke or InvokeAsync methods. If we inject dependency via the constructor, it behaves like a singleton object.

public void ConfigureServices(IServiceCollection services)
{
 ….
 …
 services.AddScoped<IHelloWorldService, HelloWorldService>();
 ….
 …
}

Scoped Example

//Step 1: Create the required service    
public interface IFirstScopedService  
{  
  string HelloWorld();  
}  
   
public class FirstScopedService: IFirstScopedService  
{  
 public string ShowMessage()  
 {  
   return "Welcome to Scholarhat Scoped";  
 }  
}  
  
//Step 2: Add above created service to Service container as below    
public void ConfigureServices(IServiceCollection services)  
{  
 // .. other code  
 services.AddScoped();  
 //.. other code  
}  
  
//Step 3: Use above created service as a dependency in the specific or required controller   
public class HomeController: Controller  
{  
 IFirstScopedService _firstScopedService;  
 public HomeController(IFirstScopedService firstScopedService)  
 {  
   _firstScopedService = firstScopedService;  
 }  
}     
Conclusion
So in this article, we have learned about service lifetimes for dependency injection. I hope you enjoyed learning these concepts while programming with .Net. Feel free to ask any questions from your side. Your valuable feedback or comments about this article are always welcome. Consider our .NET Certification Training to learn .net from scratch.

FAQs

Q1. What are service lifetimes in .NET Core?

ASP.NET Core has three main service lifetimes: Singleton, Scoped, and Transient.

Q2. What is scoped vs singleton?

Scoped objects are the same for a given request but differ across each new request. Singleton objects are the same for every request

Q3. What is a service life cycle?

It is a process used to identify the stage in which a product or service is encountering at that time
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Project Jul 16 TUE, THU
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this