π 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 Type What It Means Coffee Shop Analogy ☕ AddTransient() New instance every time A new barista is hired for each customer order . AddScoped() One instance per request A barista is assigned for an entire customer visit . AddSingleton() One instance for the entire application One 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 ...