πŸš€ Understanding AddTransient, AddScoped, and AddSingleton in C# Dependency Injection

 

When working with Dependency Injection (DI) in .NET, you’ll come across three main ways to register services:
AddTransient()
AddScoped()
AddSingleton()

But what do they mean? Let’s break them down with simple analogies!


☕ Imagine a Coffee Shop Scenario

You're running a coffee shop and serving customers. Your baristas (services) can be hired in different ways:

Lifetime TypeWhat It MeansCoffee Shop Analogy ☕
AddTransient()New instance every timeA new barista is hired for each customer order.
AddScoped()One instance per requestA barista is assigned for an entire customer visit.
AddSingleton()One instance for the entire applicationOne permanent barista serves all customers forever.

Now, let’s look at them in technical terms.


πŸ”Ή 1️⃣ AddTransient – Always Fresh (New Instance per Request)

services.AddTransient<ICoffeeService, CoffeeService>();

πŸ›  How It Works?

  • Every time you request ICoffeeService, a new instance is created.
  • Best for lightweight, stateless services.

☕ Coffee Shop Analogy:

Imagine every coffee order gets a new barista to prepare it.

  • Order 1 → Barista A ☕
  • Order 2 → Barista B ☕
  • Order 3 → Barista C ☕

✅ When to Use?

✔ When you need new, independent data every time.
✔ Great for utility services, such as sending emails, logging, or simple calculations.


πŸ”Ή 2️⃣ AddScoped – One per Request (Scoped to a Session)


services.AddScoped<ICoffeeService, CoffeeService>();

πŸ›  How It Works?

  • A single instance is created per HTTP request.
  • If multiple components need ICoffeeService within the same request, they share the same instance.

☕ Coffee Shop Analogy:

A barista is assigned to a customer visit and serves them throughout.

  • Customer 1 arrives → Assigned Barista A
  • Customer 2 arrives → Assigned Barista B
  • Customer 1 orders again → Still served by Barista A.

✅ When to Use?

✔ When you need data consistency within a request, like handling database transactions.
✔ Useful for Entity Framework Core DbContext (prevents multiple connections).


πŸ”Ή 3️⃣ AddSingleton – One for All (Same Instance for Everyone)


services.AddSingleton<ICoffeeService, CoffeeService>();

πŸ›  How It Works?

  • A single instance is created when the app starts and shared across all requests.
  • Every component gets the same instance.

☕ Coffee Shop Analogy:

A single barista serves all customers forever.

  • Customer 1 → Barista ☕
  • Customer 2 → Same Barista ☕
  • Customer 100 → Still the same Barista!

✅ When to Use?

✔ When the service does not change frequently and should be shared.
✔ Good for caching, configuration settings, and logging.


πŸ›  Code Example: Using All Three in DI Container


public void ConfigureServices(IServiceCollection services) { services.AddTransient<ICoffeeService, CoffeeService>(); // Always new services.AddScoped<IOrderService, OrderService>(); // One per request services.AddSingleton<ILogger, Logger>(); // One for the whole app }

🎯 Key Takeaways

LifetimeCreates a New InstanceShared Across Requests?Best Use Case
AddTransient()✅ Yes❌ NoLightweight, stateless services
AddScoped()✅ Yes (per request)✅ Yes (within request)Database operations, API calls
AddSingleton()❌ No (only once)✅ YesLogging, caching, config settings

πŸš€ Conclusion

Think of AddTransient, AddScoped, and AddSingleton as hiring strategies for your app’s services. Choosing the right one ensures better performance, memory management, and scalability! 🎯

πŸ”Ή Which one do you use the most? Let me know in the comments! πŸ‘‡πŸ˜Š

Comments

Popular posts from this blog

πŸ€– Copilot vs Microsoft Copilot vs Copilot Studio: What’s the Difference?

Understanding Auto-Numbering in a Multi-Transaction System

Integrating Dynamics 365 CRM with MuleSoft Using a Synchronous C# Plugin