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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more