Dependency Injection (DI) is a software design pattern used to achieve Inversion of Control (IoC) between classes and their dependencies. ASP.NET Core includes a high-performance built-in DI container.
1. The Three Service Lifetimes Explained
Selecting the wrong lifetime is one of the most common causes of memory leaks and concurrency bugs in production.
┌──────────────┬──────────────────────────────────────────┬─────────────────────────────┐
│ Lifetime │ Creation Behavior │ Common Use Cases │
├──────────────┼──────────────────────────────────────────┼─────────────────────────────┤
│ Transient │ Created EVERY time it is requested │ Stateless helpers, parsers │
│ Scoped │ Created ONCE per HTTP request │ Entity Framework DbContext │
│ Singleton │ Created ONCE on startup, shared globally │ In-memory caches, queues │
└──────────────┴──────────────────────────────────────────┴─────────────────────────────┘
Registering Services in Program.cs:
builder.Services.AddTransient<ITokenGenerator, JwtTokenGenerator>();
builder.Services.AddScoped<IUserRepository, SqlUserRepository>();
builder.Services.AddSingleton<IMetricsCollector, PrometheusMetricsCollector>();
2. The Dangerous "Scoped inside Singleton" Bug (Captive Dependencies)
A Captive Dependency occurs when a singleton service depends on a scoped service. Because the singleton lives forever, the scoped service is kept alive indefinitely, leading to memory leaks and database connection crashes!
// DANGEROUS BAD CODE:
public class BackgroundWorker : BackgroundService // Singleton
{
private readonly AppDbContext _db; // ERROR! AppDbContext is Scoped!
public BackgroundWorker(AppDbContext db)
{
_db = db; // DANGER: Captive dependency!
}
}
// CORRECT SOLUTION: Inject IServiceScopeFactory
public class BackgroundWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
public BackgroundWorker(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Manually create an explicit scope per iteration
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.ProcessQueueAsync(stoppingToken);
}
}