Dependency Injection Lifetimes in ASP.NET Core

πŸ’‘ Concept Name

Service Lifetimes: Transient, Scoped, Singleton

πŸ“˜ Quick Intro

In ASP.NET Core, Dependency Injection (DI) allows you to control the lifespan of services using three main lifetimes: Transient, Scoped, and Singleton. Choosing the correct lifetime is crucial for application performance and behavior.

🧠 Analogy / Short Story

Imagine a coffee shop:

  • Transient: Every time you ask for coffee, you get a new cup (new instance).
  • Scoped: One person (user request) gets one coffee cup for the entire visit (one instance per request).
  • Singleton: There’s only one shared coffee pot for everyone (one instance for the entire app lifecycle).

πŸ”§ Technical Explanation

Transient: A new instance is provided every time the service is requested. Use for lightweight, stateless services.

Scoped: A single instance is created per request. Useful for services that hold request-specific state (like DbContext).

Singleton: A single instance is created and shared across the entire application. Ideal for caching or configuration providers.

Use the following methods in Startup.cs or Program.cs to register services:


builder.Services.AddTransient<IMyService, MyService>();
builder.Services.AddScoped<IMyService, MyService>();
builder.Services.AddSingleton<IMyService, MyService>();
            

🎯 Purpose & Use Case

  • βœ… Use Transient for stateless services with lightweight dependencies
  • βœ… Use Scoped for services dealing with HTTP request data (like DbContext)
  • βœ… Use Singleton for services that are expensive to create or need to be shared

πŸ’» Real Code Example

Registering services with different lifetimes in Program.cs:


var builder = WebApplication.CreateBuilder(args);

builder.Services.AddTransient<IEmailSender, EmailSender>();
builder.Services.AddScoped<IRepository, EfRepository>();
builder.Services.AddSingleton<IConfigService, ConfigService>();

var app = builder.Build();
app.Run();
            

❓ Interview Q&A

Q1: What are the 3 DI lifetimes in ASP.NET Core?
A: Transient, Scoped, Singleton.

Q2: When should you use Transient services?
A: When you want a new instance for every request.

Q3: What is Scoped lifetime used for?
A: For creating one instance per HTTP request.

Q4: How long does a Singleton instance live?
A: For the entire lifetime of the application.

Q5: Can Singleton depend on Scoped or Transient?
A: Not safelyβ€”can lead to capturing disposed objects.

Q6: Where do you configure service lifetimes?
A: Inside Program.cs or Startup.cs using AddXXX methods.

Q7: Which lifetime is best for a service using DbContext?
A: Scoped.

Q8: Can services be injected into middleware?
A: Yes, via constructor injection or HttpContext.RequestServices.

Q9: What problems occur if Singleton service depends on Scoped service?
A: It may use disposed objects and cause runtime errors.

Q10: How can you resolve lifetimes conflicts in DI?
A: Avoid Singleton depending on Scoped; restructure dependencies.

πŸ“ MCQs

πŸ“ MCQs

Q1. What does Transient lifetime mean in ASP.NET Core DI?

  • Same instance per request
  • New instance every time
  • Shared globally
  • Static lifetime

Q2. Which lifetime creates one instance per HTTP request?

  • Singleton
  • Scoped
  • Transient
  • Static

Q3. Which method registers a singleton service?

  • AddTransient
  • AddScoped
  • AddSingleton
  • RegisterService

Q4. Which lifetime is ideal for lightweight, stateless services?

  • Singleton
  • Scoped
  • Transient
  • Static

Q5. What happens if you use scoped services in singleton constructor?

  • It works fine
  • Runtime error
  • Captures wrong lifetime
  • Loads eagerly

Q6. Which DI lifetime can cause memory leaks if misused?

  • Transient
  • Scoped
  • Singleton
  • All of the above

Q7. Which lifetime is resolved once and reused throughout app life?

  • Scoped
  • Singleton
  • Transient
  • Stateless

Q8. Is it valid to inject a transient service into a scoped one?

  • Yes
  • No
  • Only in Startup
  • Only in Controllers

Q9. What is the default DI container in ASP.NET Core?

  • Autofac
  • SimpleInjector
  • Built-in Microsoft.Extensions.DependencyInjection
  • Ninject

Q10. When is a scoped service disposed?

  • At the end of app lifetime
  • Never
  • At the end of request
  • During garbage collection

πŸ’‘ Bonus Insight

Misusing lifetimes can lead to memory leaks or bugs. Always understand the context in which your service operates before assigning a lifetime.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

Learn More About ASP.NET Core πŸš€

What is ASP.NET Core? πŸ‘‰ Explained
ASP.NET Core vs .NET Framework πŸ‘‰ Explained
Role of Kestrel Server in ASP.NET Core πŸ‘‰ Explained
Middleware & Request Pipeline πŸ‘‰ Explained
Dependency Injection in ASP.NET Core πŸ‘‰ Explained
Program.cs vs Startup.cs πŸ‘‰ Explained
Configuration & appsettings.json πŸ‘‰ Explained
Environment-specific settings πŸ‘‰ Explained
Writing Custom Middleware πŸ‘‰ Explained
Logging in ASP.NET Core πŸ‘‰ Explained
Static File Middleware πŸ‘‰ Explained
Routing fundamentals πŸ‘‰ Explained
Model Binding & Validation πŸ‘‰ Explained
Razor Pages vs MVC πŸ‘‰ Explained
Tag Helpers overview πŸ‘‰ Explained
Filters in MVC (Action, Authorization, Exception) πŸ‘‰ Explained
Web API controllers & content negotiation πŸ‘‰ Explained
Versioning ASP.NET Core Web API πŸ‘‰ Explained
Entity Framework Core introduction πŸ‘‰ Explained
Code-First vs Database-First in EF Core πŸ‘‰ Explained
Migrations in EF Core πŸ‘‰ Explained
LINQ fundamentals πŸ‘‰ Explained
Async/Await and async controllers πŸ‘‰ Explained
Error & Exception Handling Middleware πŸ‘‰ Explained
CORS configuration & usage πŸ‘‰ Explained
Authentication vs Authorization πŸ‘‰ Explained
ASP.NET Core Identity basics πŸ‘‰ Explained
JWT Authentication integration πŸ‘‰ Explained
Caching strategies πŸ‘‰ Explained
Session & State Management πŸ‘‰ Explained
File Upload handling πŸ‘‰ Explained
Health Checks & monitoring πŸ‘‰ Explained
Hosted Services & Background Tasks πŸ‘‰ Explained
Working with IWebHostEnvironment πŸ‘‰ Explained
IWebHostBuilder and WebHost vs Generic Host πŸ‘‰ Explained
Deployment to IIS, Kestrel, Nginx, Docker πŸ‘‰ Explained
Use of HTTP.sys Server πŸ‘‰ Explained
Configuration providers (JSON, env, CLI) πŸ‘‰ Explained
Handling Concurrency in EF Core πŸ‘‰ Explained
Model validation & custom validation πŸ‘‰ Explained
Dependency Injection service lifetimes πŸ‘‰ Explained
Security best practices (HTTPS, HSTS, CSP) πŸ‘‰ Explained
Authorization policies & claims πŸ‘‰ Explained
Rate limiting & request throttling πŸ‘‰ Explained
Health & metrics integration πŸ‘‰ Explained
Swagger/OpenAPI documentation πŸ‘‰ Explained
Blazor fundamentals πŸ‘‰ Explained
Razor Class Libraries (RCL) πŸ‘‰ Explained
SignalR real-time communication πŸ‘‰ Explained
Performance optimization & profiling πŸ‘‰ Explained
Share:

Tags:


Feedback Modal Popup