By : Muhammad Waseem Last edited : 18 Nov 2024 Level: Intermediate A: When registering services in the DI container, you can specify their lifetimes, which determine how and when instances are created and shared. The three main lifetimes are Scoped, Transient, and Singleton.
Scoped: A new instance of the service is created once per request or scope. This is useful for services that need to maintain state within a single request but should not share state across requests. In web applications, a new scope is created for each HTTP request.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<ICustomerService, CustomerService>();
Transient: A new instance of the service is created each time it is requested. This is ideal for lightweight, stateless services that do not hold any state between requests. Transient services can lead to higher memory consumption if not managed properly, as a new instance is created every time.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<ICustomerService, CustomerService>();
Singleton: A single instance of the service is created and shared throughout the application’s lifetime. This is suitable for services that maintain state or are expensive to create. Singleton services are created the first time they are requested or when the application starts, depending on the implementation.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ICustomerService, CustomerService>();