AddTransient AddScoped and AddSingleton Services in ASP.NET Core MVC

Service Lifetime is the duration for any services persist in Dependecy Injection Conatiner of any application. It is a way to representing the timeline of services that specify the time how long the Container will keep the instances of any requested services in DI conatiner after creation of these instances.

Dependency Injection Container :- is a place where we register the services and DI conatiner manages these service instances and configure their Objects for an application based on the service type we used for registering the Services in DI Container.
It is the responsibility of the DI Container to keep track on created services and disposal of these services when it is not required or completed the lifetime.
Whenever application requested for any services DI Container is the only responsible to create the instances of the required services at runtime based on their service type by which it is registered in DI Conatiner.

There are three types of services lifetime we used for registering the services are specified below.

  • AddTransient Services :- Transient Services creates a new instance every time when it is requested and it does not matter request is same or different. These kind of services is best suitable for lightweight applications as well as Stateless applications.
  • AddScoped Services :- For each request one service instance is created and reused for throughout the request. In simple words we can say that it is User specific means created for each user(Single HTTP Request) and shared across all the request.
  • AddSingleton Services :- In Singleton Services as name suggest it creates only Single instance for the service and used globally throughout the application. In simple words only one instance is created and shared by all the Users.

Implementation of Services in MVC Core application :- I have explained the services implementation in details using a Example in which you can easily understand the differences between AddTransient, AddScoped and Singleton services.
Below is the steps that i have used in my application for services implementation you can follow the same steps in your application also.

  • Create the seperate Interface for each service and declare a method that will return a new GUID.
  • Create a ServiceRequest class and implement the these three interfaces into the same class and define the method details that is returning thr new GUID.
  • Register these services class into the Program.cs file with AddTransient, AddScoped and AddSingleton service types.
  • Create a Constructor in Controller and use the two different dependency objects for each type and assigned it to the properties.
  • Now call the ServiceClass Methods using different dependency objects and store the return GUID values in ViewBags and return it to the view.
  • Create a View and use the Viewbags variable for services and displays them into the tabular format.
  • Run the application and check it for two different tabs of browser or UI then you can see the difference between these three services in the terms of instance creation and sharing of them between requests.

Below code is for displaying these three Interfaces created for each services.

                
public interface IScopedServiceType
    {
        Guid GetRequestID();
    }           
                
                
public interface ITransientServiceType
    {
        Guid GetRequestID();
    }           
                
                
 public interface ISingletonServiceType
    {
        Guid GetRequestID();
    }           
                

Below is the code example for ServiceRequestClass that is implementing these three Interfaces.

                
 public class ServiceRequestClass : ISingletonServiceType, IScopedServiceType, ITransientServiceType
    {
        Guid UniqueId;
        public ServiceRequestClass()
        {
            UniqueId = Guid.NewGuid();
        }
        public Guid GetRequestID()
        {
            return UniqueId;
        }
    }           
                
Image is not available

After creating the Interfaces and Service class you need to register these services into the DI Container in Program.cs file as shown in below Image and Program.cs file code.

Image is not available
                
 using BloggingExamples.Data;
    using Microsoft.EntityFrameworkCore;

    var builder = WebApplication.CreateBuilder(args);

    // Add services to the container.
    builder.Services.AddControllersWithViews();
    builder.Services.AddDbContext(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DBCS")));
    builder.Services.AddScoped (ScopedServiceType, ServiceRequestClass)();
    builder.Services.AddTransient(ITransientServiceType, ServiceRequestClass)();
    builder.Services.AddSingleton(ISingletonServiceType, ServiceRequestClass)();
    var app = builder.Build();

    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
    }
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();

    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=AspCoreService}/{action=CheckServiceType}/{id?}");

    app.Run();
                 
                

After registering the Services into Program.cs file now we need to use them in controller using the constructor dependency injection as shown in below Image and code snippet.

Image is not available
                
  public class AspCoreServiceController : Controller
    {
        private readonly IScopedServiceType _servicesScoped;
        private readonly ITransientServiceType _servicesTransient;
        private readonly ISingletonServiceType _servicesSingleton;
        private readonly IScopedServiceType _servicesScoped2;
        private readonly ITransientServiceType _servicesTransient2;
        private readonly ISingletonServiceType _servicesSingleton2;
        public AspCoreServiceController(IScopedServiceType scopedServiceType,ITransientServiceType transientServiceType,
            ISingletonServiceType singletonServiceType, IScopedServiceType scopedServiceType2, ITransientServiceType transientServiceType2,
            ISingletonServiceType singletonServiceType2)
        {
            _servicesScoped = scopedServiceType;
            _servicesTransient = transientServiceType;
            _servicesSingleton = singletonServiceType;
            _servicesScoped2 = scopedServiceType2;
            _servicesTransient2 = transientServiceType2;
            _servicesSingleton2 = singletonServiceType2;
        }
        public IActionResult CheckServiceType()
        {
            ViewBag.ScopeTypeFirstRequest = _servicesScoped.GetRequestID();
            ViewBag.ScopeTypeSecondRequest = _servicesScoped2.GetRequestID();
            ViewBag.TransientTypeFirstRequest = _servicesTransient.GetRequestID();
            ViewBag.TransientTypeSecondRequest = _servicesTransient2.GetRequestID();
            ViewBag.SingletonTypeFirstRequest = _servicesSingleton.GetRequestID();
            ViewBag.SingletonTypeSecondRequest = _servicesSingleton2.GetRequestID();
            return View();
        }
    }           
                

Create a View and use the Viewbag stored GUID from different requests as you can see into the below image that is for a cshtml view of the Action method.

Image is not available

Now run the application in two tabs we are considering it as a Request Number 1 and you can see into the table for different service types has different request Id for Request in single browser.
First Request

Image is not available

Now run the application in two different browsers and we are considering it as a Request Number 2 and you can see into the table for different service types has different request Id for Request in both the browsers.
Second Request

Image is not available

Conclusion :- As you can see into above images we conclude that Transient services created different instances for each and every request and Scoped Services created a single instance for a specific HTTP request and share that to throughout but for other request it is different from first one. Singleton services are created only single instance for a request and used globally all over the application.


Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.