Service lifetime – .NET Core

There are 3 service lifetime available in .NET Core with Dependency Injection. They are Transient, Scoped and Singleton.

As you know that Dependency Injection is at the core of .Net Core. To register dependency injection in .Net Core application we use startup.cs file.

In this article, we will look into the 3 service lifetime in .NET Core by which we can register Dependency Injection and we will see what are the difference among them.

AddTransient

The AddTransient method creates a new instance every time a service request is raised, doesn’t matter it is in the same HTTP request or a different HTTP request. So, the service registered with Transient lifetime are created every time they gets inject into a class.

AdScoped

With AddScope() method, we get new instance with different HTTP requests. But we get the same instance if it is within the same scope.

In easy words, a service instance is created for a request and reused throughout the scope of the request.

AddSingleton

In AddSingleton() method, only one instance of service is created, when the service is executed for very first time. So, a single instance is created for a service, no matter how many times the service is being executed.

So, in Singleton lifetime, only one service instance is created and then shared across further requests.

Read ASP.Net Core Interview Questions and Answers

Syntax to register Dependency Injection

Below are the code snippet, using this we can register the Dependency Injection within ConfigureService() method available in startup.cs file.

 public void ConfigureServices(IServiceCollection services)
        {
            
            //Transient 
            services.AddTransient<ITransientService, LifeCycleTest>();
            //Scoped
            services.AddScoped<IScopedService, LifeCycleTest>();
            //Singleton
            services.AddSingleton<ISingletonService, LifeCycleTest>();
        }

Watch AddTransient, AddScoped and AddSingleton Service demonstration in below video

Summary –

  • Transient objects are always different.
  • Scoped objects are same if the request generated from the same scope.
  • Singleton objects are always same and they use memory to serve the same objects, if you restart the service/ server then only Singleton object gets changed.
  • If you are not sure about which one to use to register Dependency Injection then use AddTransient method only.
  • Singleton objects are expensive as they uses memory, every time a request is generated.
You may read this - How to implement Dependency Injection in .NET 5?

1 thought on “Service lifetime – .NET Core”

Leave a Comment

RSS
YouTube
YouTube
Instagram