SOLID & Design Patterns Interview Question #143
What is the difference between Transient, Scoped, and Singleton DI lifetimes?
Anti-Patterns, Refactoring, DI Lifetimes & Senior Design Scenarios Senior Advanced
Quick Interview Answer
Transient creates a new instance whenever the service is resolved. Scoped reuses one instance within a scope, typically one HTTP request. Singleton reuses one instance for the application's container lifetime.
Detailed Explanation
Transient creates a new instance whenever the service is resolved. Scoped reuses one instance within a scope, typically one HTTP request. Singleton reuses one instance for the application's container lifetime.
Choose lifetime based on state, resource ownership, thread safety, and dependencies. A longer-lived service must not capture a shorter-lived dependency through normal constructor injection.
Code Example
builder.Services.AddTransient<IFormatter, Formatter>();
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddSingleton<ISystemClock, SystemClock>();