Service Lifetime with Dependency Injection in Asp.Net Core
The ASP.NET Core provides 3 methods to register a service with the ASP.NET Core Dependency Injection container.
The method that we use to register a service will determine the lifetime of that service.
In this case, the IoC container will create and share a single instance of a service object throughout the application’s lifetime.
ASP.NET Core will create and share a single instance of the service through the application life.
This can be achieved by adding the service as a singleton through the AddSingleton method of the IServiceCollection.
ASP.NET Core will take care of creating the service instance during registration, and subsequent requests will use this same instance.
There is no need to implement a singleton design pattern as ASP.NET Core handles the single instance itself.
In this case, the IoC container will create a new instance of the specified service type every time you ask for it.
ASP.NET Core will create and share a new instance of the service every time to the application when we ask for it, whether it is in the scope of same HTTP request or across different HTTP requests.
The service can be added as Transient using the AddTransient method of IServiceCollection.
This lifetime can be used in stateless service (while calling through API). 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.
In this case, the IoC container will create an instance of the specified service type once per request and will be shared in a single request.
ASP.NET Core will create and share the same instance within the scope of a given HTTP request but a new instance across different HTTP requests 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.
Note: The Built-in IoC container manages the lifetime of a registered service. It automatically disposes of a service instance based on the specified lifetime.
Lets Create Service, Interface and Register in Program.cs file