Explain dependency injection in ASP.NET Core (Transient, Scoped, Singleton)

4 minintermediateASP.NET-Coredependency-injectionlifetimes

Quick Answer

ASP.NET Core has built-in DI; services are registered with a lifetime that controls instance reuse. Transient creates a new instance every time it's requested; Scoped creates one instance per HTTP request (shared within that request); Singleton creates one instance for the app's lifetime. Match lifetime to state/thread-safety needs, and never inject a shorter-lived (e.g., Scoped) service into a Singleton.

Detailed Answer

Dependency Injection (DI) is a built-in design pattern in ASP.NET Core that achieves Inversion of Control (IoC) between classes and their dependencies. Services are registered with specific lifetimes.

Service Lifetimes:

4.3.1. Transient

  • A new instance is created every time the service is requested
  • Best for lightweight, stateless services
  • Registered using AddTransient<TService, TImplementation>()
services.AddTransient();

Use case: Operations that don't maintain state, like sending emails or generating random numbers.

4.3.2. Scoped

  • A single instance is created per client request (HTTP request)
  • The same instance is used throughout the entire request
  • Registered using AddScoped<TService, TImplementation>()
services.AddScoped();

Use case: Database contexts (Entity Framework), repository patterns, services that need to maintain state during a request.

4.3.3. Singleton

  • A single instance is created for the entire application lifetime
  • The same instance is shared across all requests
  • Registered using AddSingleton<TService, TImplementation>()
services.AddSingleton();

Use case: Configuration, logging, caching services, thread-safe services.

Registration example in Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Transient
builder.Services.AddTransient();

// Scoped
builder.Services.AddScoped();

// Singleton
builder.Services.AddSingleton(builder.Configuration);

var app = builder.Build();

Important considerations:

  • Avoid injecting scoped or transient services into singleton services (causes memory leaks)
  • Singleton services must be thread-safe
  • Scoped is the most commonly used lifetime for business logic