Service Lifetimes in Dependency Injection (DI) – ASP.NET Core

In ASP.NET Core, Dependency Injection (DI) is a built-in feature that manages the creation, disposal, and lifetime of services. A key aspect of DI is understanding Service Lifetimes, which define how long a service instance lives in the application.

There are three primary lifetimes:

  • Transient
  • Scoped
  • Singleton

Each lifetime affects how and when service objects are created and reused.



1️⃣ Transient

  • A new instance is created every time the service is requested.
  • Best for lightweight, stateless services.
  • Multiple calls within a single request → multiple instances.
services.AddTransient<IMyService, MyService>();

Behavior:

  • Request A → new MyService()
  • Request B → new MyService()
  • Multiple times in same request → different instances

2️⃣ Scoped

  • One instance per HTTP request (or per DI scope).
  • Same instance reused throughout the request.
  • Great for services tied to request-specific state like DB context.
services.AddScoped<IMyService, MyService>();

Behavior:

  • Request A → one MyService instance
  • Request B → new instance
  • Multiple times in same request → same instance reused

3️⃣ Singleton

  • One instance for the entire lifetime of the application.
  • All consumers across all requests get the same instance.
  • Best for shared, stateless, and thread-safe services (like caching, logging).
services.AddSingleton<IMyService, MyService>();

Behavior:

  • All requests → same instance of MyService
  • Created at startup or on first use

📊 Lifetime Comparison Table

Lifetime Instance Created Shared per Request Shared Across Requests Best Use Case
Transient Every time No No Lightweight, stateless services
Scoped Once per request Yes No Per-request services (e.g., DbContext)
Singleton Once per app Yes Yes App-wide services (e.g., config, cache)
💡 Tip: Avoid injecting Scoped services into Singleton services. It can lead to memory leaks and unexpected behavior.

✅ Summary

Choosing the correct lifetime helps optimize performance, memory usage, and code maintainability in ASP.NET Core applications.

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features