.NET Core Service Lifetimes

INexLin
Oct 30, 2020

Service can be registered with the following lifetimes:

  • Transient

A new instance is created each time when you request service from container

  • Scoped

A new instance is created once per client request

  • Singleton

Only create one time per application

More details you can visit this website as below:

Here’s a sample that help you to learn more about DI lifetimes

There are three interfaces all inherit ILifetime which is an interface with id property

And LifetimeService implement these three interface

Register services with three di lifetimes in Startup ConfigureServices

public void ConfigureServices(IServiceCollection services){  services.AddControllers();  services.AddSingleton<ISingletonService, LifetimeService>();  services.AddTransient<ITransientService, LifetimeService>();  services.AddScoped<IScopedService, LifetimeService>();}

TestController injection these three services

Let’s test with postman

The singleton_id in Test #1 and Test #2 are the same but the transient_id and scoped_id are different.

Test #1

Test #2

In this sample can’t recognize the different between “Scoped” and “Transient”. Therefore, “DILifeTimeService” is created with injection three services

The Startup and TestController are also added some code

Let’s test with postman again

New instance of service is created once per client request when you use “Scoped” so that in this sample scoped_id and scoped_DIService_id are the same. Although, IScopedService is injected in different class.

Test #3

view all code in github

--

--