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!