Interview frequency: …
Short answer
Transient creates a new instance on each injection, Scoped creates one instance per HTTP request shared by its components, and Singleton creates one instance shared for the process lifetime.
Explanation
Service lifetime management is fundamental to Dependency Injection. Use Transient for lightweight, stateless services; Scoped for services that hold request state or share a context such as Entity Framework DbContext; and Singleton for expensive services that keep shared cache memory or manage persistent network sockets.
Code example
builder.Services.AddTransient<IEmailSender, EmailSender>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddSingleton<ICacheManager, MemoryCacheManager>();Common mistakes
- Injecting a Scoped service into a Singleton service, creating a serious Captive Dependency problem.
Follow-up questions
- What is Captive Dependency in the .NET DI container, and how do you detect and prevent it?
- Who calls Dispose() on services implementing IDisposable when using the .NET DI container?