DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

How many ways we can maintain the life cycle of service in Asp.Net Core

In ASP.NET Core, there are several ways to maintain the lifecycle of a service. Here are the most common approaches:

Transient:

Transient services are created each time they are requested. A new instance is created for each dependency injection request, and the instance is not shared between multiple components. This is useful for lightweight and stateless services.

Example

services.AddTransient<IService, TransientService>();
Enter fullscreen mode Exit fullscreen mode

Scoped:

Scoped services are created once per client request (HTTP request in web applications). The same instance is used throughout the entire request, but different requests will have different instances. Scoped services are commonly used for services that need to maintain state during a request.

Example

services.AddScoped<IService, ScopedService>();
Enter fullscreen mode Exit fullscreen mode

Singleton:

Singleton services are created only once during the lifetime of the application. The same instance is shared across all requests and components within the application. Singleton services are suitable for services that are expensive to create or need to maintain a global state.
To specify the lifecycle of a service in ASP.NET Core, you can use the AddTransient, AddScoped, and AddSingleton methods when registering services in the dependency injection container.

Example

services.AddSingleton<IService, SingletonService>();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)