ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

ASP.NET Core Tutorial• 8 min read

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.

Registering and Injecting Services
// 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());
}
Constructor injection ensures loose coupling and makes components effortless to unit test with mocks.
LifetimeRegistration MethodInstance Frequency
TransientAddTransient<T>()New instance every single time requested
ScopedAddScoped<T>()Single instance per HTTP client request
SingletonAddSingleton<T>()One shared instance for the entire server process
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which service lifetime creates a single instance per client HTTP request, making it ideal for DbContext database sessions?