Introduction

In ASP.NET Core's dependency injection (DI) system, you have three options for registering services: AddTransient, AddScoped, and AddSingleton. These options control the lifecycle and behavior of the registered services. Let's explore these concepts with a simple restaurant example.

AddTransient

Syntax

services.AddTransient<ITableService, TableService>();

AddScoped

Syntex

services.AddScoped<IWaiterService, WaiterService>();

AddSingleton

Syntex

services.AddSingleton<IChefService, ChefService>();

Here's how you might use these service lifetimes in an ASP.NET Core application.

public void ConfigureServices(IServiceCollection services) {
    // Transient: New waiter for each table (per request)
    services.AddTransient<ITableService, TableService>();

    // Scoped: One waiter per group of customers (per request)
    services.AddScoped<IWaiterService, WaiterService>();

    // Singleton: One head chef for the entire restaurant (shared)
    services.AddSingleton<IChefService, ChefService>();
}

In practice, your choice of service lifetime depends on the behavior and requirements of the services in your application. Stateful services that need to maintain data between requests might use AddScoped, while stateless services can be registered as AddTransient. Services shared globally across the application can be registered as AddSingleton.