Skip to main content
InterviewHubPRO
Section Overview
Q2

Question 2 of 50

Part 1: Request Pipeline, Dependency Injection & Web APIs (1 - 10)

4%
ASP.NET Core & Web API (50 Qs)•Part 1: Request Pipeline, Dependency Injection & Web APIs (1 - 10)

Explain Dependency Injection Lifetimes in ASP.NET Core: Transient vs. Scoped vs. Singleton.

mid LevelMost AskedCode ExampleDependency InjectionPipesCI/CD & DevOps

In Simple Words:

  • Transient (AddTransient): New instance created every single time it is requested. Best for lightweight, stateless services.
  • Scoped (AddScoped): Exactly one instance created per HTTP request lifecycle. Best for services that share state within a single request (e.g., DbContext).
  • Singleton (AddSingleton): Exactly one instance created on first request and shared across the entire application lifetime. Must be 100% thread-safe (e.g., memory caches, telemetry clients).
  • Captive Dependency Warning: Injecting a Scoped service into a Singleton service extends the scoped service's lifetime to singleton, causing concurrency bugs and memory leaks.
csharp
builder.Services.AddTransient<IEmailSender, SmtpEmailSender>();
builder.Services.AddScoped<IOrderService, OrderService>(); // Per HTTP request
builder.Services.AddSingleton<IMemoryCache, MemoryCache>(); // App lifetime