⚙️ C# / .NET Intermediate

What is the difference between AddSingleton, AddScoped, and AddTransient?

Answer

These are the three service lifetime options in ASP.NET Core's DI container. AddSingleton: one instance for the entire application lifetime — created once on first request, shared across all requests and threads. Use for: stateless services, configuration, in-memory caches, HttpClient (via IHttpClientFactory). Thread-safety required. AddScoped: one instance per HTTP request (scope). All components within the same request share the same instance. Disposed at the end of the request. Use for: DbContext (critical — one transaction per request), UnitOfWork, business services. AddTransient: new instance every time the service is requested from the container. Use for: lightweight, stateless services with no shared state. Captive dependency problem: injecting a scoped service into a singleton causes the scoped service to behave like a singleton (lives for the application lifetime) — the container throws an exception in development. Never inject scoped or transient services into singletons.