Service Lifetimes: Transient, Scoped, Singleton
Learn how Transient, Scoped, and Singleton lifetimes affect object creation, sharing, and disposal.
Why Lifetimes Matter
Service lifetime controls how long an instance lives and how many instances are created. Picking the wrong lifetime causes subtle bugs like data leaks between requests or excessive object creation.
Transient: New Every Time
Transient services are created fresh every time they are requested from the container. Use them for lightweight, stateless services where sharing state would be dangerous.
builder.Services.AddTransient<IEmailSender, SmtpEmailSender>();
// Each resolution creates a new instance:
// var a = sp.GetRequiredService<IEmailSender>(); // new
// var b = sp.GetRequiredService<IEmailSender>(); // new (different)All lessons in this course
- DI Container Fundamentals
- Service Lifetimes: Transient, Scoped, Singleton
- Constructor Injection & Interfaces
- Factory & Options Patterns