.NET core Service lifetimes (AddTransient vs AddScoped vs AddSingle)

Unlike .net framework , .net core has provided built-in dependency injection feature. In order to register any service with Microsoft Dependency Injection Container , .net core provides with three different methods

  1. AddTransient
  2. AddScoped
  3. AddSingleton

AddTransient

If any service is registered with Transient lifetime , then always a new instance of that service is created when ever service is requested.

In the above code snippet , i have created an interface with one method.

I have created a class and implementing the interface IServiceLifetime.

In Startup file , i have injected our service as Transient scope.

In above controller , i have injected IServiceLifetime in the constructor.

In the above class, i have injected the dependency IServiceLifetime in constructor and in GetAllFirms method i have written a console statement which prints Guid.

In above example , i have injected our service in controller and other class.

Below is the output.

As in the above screen shot , new Guid is created whenever the instance of service is requested (in our example we injected our service in controller and other class)

AddScoped

If any service is registered with Scoped lifetime , then new instance of that service is created for every request.

If we register service as scoped as above , below is the output:-

In the above screenshot its very that for a single request same instance returned always if service is registered as scoped.

Try to make another request , you will see different Guid.

AddSingleton

If any service is registered with Singleton lifetime , then instance of that service is created only once and later same instance of that service is used in the entire application.

If you see the above screenshot , irrespective of any number of request , always same instance is returned.

Full stack developer