Understanding Service Lifetimes in .Net Core

Understanding Service Lifetimes in .Net Core

26 Apr 2024
Beginner
103 Views
6 min read

Service lifetimes in .Net Core: An Overview

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. So we do not care about cleaning these dependencies, it will take care of the ASP.net core framework. In this .NET core tutorial, we will explore more about the Service lifetimes for dependency injection. Also, consider learning the ASP.NET Core Course for a better understanding of .net concepts. Now Let's see what service lifetimes are in net core.

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 Training Batches Schedule
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.
Self-paced Membership
  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this