Set your Publisher ID in src/config/ads.ts to display live ads.
Dependency Injection (DI) & Service Lifetimes
Understanding Transient, Scoped, and Singleton IoC container lifetimes
ASP.NET Core includes a built-in Inversion of Control (IoC) container that manages object creation and dependency resolution throughout the application lifecycle.
The Three Service Lifetimes
Transient (AddTransient): Created each time they are requested. Ideal for lightweight, stateless services.
Scoped (AddScoped): Created once per client HTTP request connection. The standard lifetime for Entity Framework DbContext and business repositories.
Singleton (AddSingleton): Created once upon initial request (or application startup) and shared by every subsequent request throughout the application lifetime. Ideal for caching or telemetry clients.
// 1. Interface and Implementation
public interface ICourseCatalogService
{
IEnumerable<string> GetFeaturedCourses();
}
public class CourseCatalogService : ICourseCatalogService
{
public IEnumerable<string> GetFeaturedCourses() =>
new[] { "Cloud Native .NET 8", "Kubernetes Microservices", "C# Deep Dive" };
}
// 2. Register in Program.cs
builder.Services.AddScoped<ICourseCatalogService, CourseCatalogService>();
// 3. Inject into a Controller or Minimal API via constructor
[ApiController]
[Route("api/[controller]")]
public class CoursesController : ControllerBase
{
private readonly ICourseCatalogService _catalogService;
public CoursesController(ICourseCatalogService catalogService)
{
_catalogService = catalogService;
}
[HttpGet("featured")]
public IActionResult GetFeatured() => Ok(_catalogService.GetFeaturedCourses());
}| Lifetime | Registration Method | Instance Frequency |
|---|---|---|
| Transient | AddTransient<T>() | New instance every single time requested |
| Scoped | AddScoped<T>() | Single instance per HTTP client request |
| Singleton | AddSingleton<T>() | One shared instance for the entire server process |
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
Which service lifetime creates a single instance per client HTTP request, making it ideal for DbContext database sessions?