Skip to main content

Lesson 2 of 8

DI Container - Service Lifetimes Deep Dive

Choosing the wrong service lifetime is one of the most common ASP.NET Core bugs - it causes data leaks, subtle threading issues, and intermittent failures. Understanding exactly when each lifetime creates and disposes instances is critical.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Transient, Scoped & Singleton - Internals

Transient, Scoped & Singleton - Internals
// ━━ Transient - new instance EVERY injection ━━
// Use for: lightweight, stateless services. Fast to create.
// Never use for: anything holding state, DB contexts, connections
builder.Services.AddTransient<IEmailValidator, EmailValidator>();

// ━━ Scoped - ONE instance per HTTP request ━━
// Shared within the same request, disposed at request end
// Use for: DB contexts (EF Core), unit of work, per-request state
builder.Services.AddScoped<AppDbContext>();
builder.Services.AddScoped<IProductService, ProductService>();

// ━━ Singleton - ONE instance for app lifetime ━━
// Created on first use, never disposed until app shuts down
// Use for: caches, HttpClient wrappers, config objects, thread-safe services
// DANGER: if Singleton captures Scoped, Scoped won't be disposed per-request → memory leak
builder.Services.AddSingleton<IMemoryCache, MemoryCache>();

// ━━ Captive dependency - the #1 DI bug ━━
// BAD: Singleton captures a Scoped service - Scoped is effectively Singleton
public class BadSingletonService(IProductRepository scopedRepo) { }
// scopedRepo will NEVER be disposed - EF Core DbContext leak!
// Fix: use IServiceScopeFactory to create a new scope when needed

// GOOD: Singleton that creates its own scope when needed
public class BackgroundEmailSender(IServiceScopeFactory scopeFactory) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        while (!ct.IsCancellationRequested)
        {
            // Create a fresh scope for each iteration - proper lifecycle
            using var scope = scopeFactory.CreateScope();
            var emailService = scope.ServiceProvider.GetRequiredService<IEmailService>();
            await emailService.SendPendingEmailsAsync(ct);
            await Task.Delay(TimeSpan.FromMinutes(1), ct);
        }
    }
}

// ━━ Scope validation in development ━━
// ASP.NET Core automatically validates scopes in Development:
// Adding a Scoped type to Singleton → throws InvalidOperationException at startup
// builder.Services.AddTransient<ISomething>() + captive singleton → detected ← great!

interface IEmailValidator { }
class EmailValidator : IEmailValidator { }
interface IEmailService { Task SendPendingEmailsAsync(CancellationToken ct); }
interface IMemoryCache { }
class MemoryCache : IMemoryCache { }

Factory Delegates & Keyed Services (.NET 8)

Factory Delegates & Keyed Services (.NET 8)
// ━━ Keyed services (.NET 8) - multiple implementations of same interface ━━
// Problem: need different notification strategies based on type
builder.Services.AddKeyedScoped<INotificationService, EmailNotificationService>("email");
builder.Services.AddKeyedScoped<INotificationService, SmsNotificationService>("sms");
builder.Services.AddKeyedScoped<INotificationService, PushNotificationService>("push");

// Inject with [FromKeyedServices] attribute:
public class OrderService(
    [FromKeyedServices("email")] INotificationService emailNotifier,
    [FromKeyedServices("sms")] INotificationService smsNotifier)
{
    public async Task NotifyOrderShipped(Order order)
    {
        await emailNotifier.SendAsync($"Order {order.Id} shipped!", order.CustomerEmail);
        if (order.Customer.PhoneVerified)
            await smsNotifier.SendAsync($"Order {order.Id} shipped!", order.Customer.Phone);
    }
}

// ━━ Factory delegate - decide implementation at runtime ━━
builder.Services.AddTransient<Func<string, IStorageService>>(provider => key => key switch
{
    "local" => provider.GetRequiredService<LocalStorageService>(),
    "s3"    => provider.GetRequiredService<S3StorageService>(),
    "azure" => provider.GetRequiredService<AzureBlobStorageService>(),
    _       => throw new ArgumentException($"Unknown storage: {key}")
});

// Use the factory:
public class FileController(Func<string, IStorageService> storageFactory)
{
    private readonly IStorageService _storage =
        storageFactory(Environment.GetEnvironmentVariable("STORAGE_PROVIDER") ?? "local");
}

// Placeholder types
interface INotificationService { Task SendAsync(string message, string recipient); }
class EmailNotificationService : INotificationService { public Task SendAsync(string m, string r) => Task.CompletedTask; }
class SmsNotificationService   : INotificationService { public Task SendAsync(string m, string r) => Task.CompletedTask; }
class PushNotificationService  : INotificationService { public Task SendAsync(string m, string r) => Task.CompletedTask; }
interface IStorageService { }
class LocalStorageService  : IStorageService { }
class S3StorageService     : IStorageService { }
class AzureBlobStorageService : IStorageService { }
record Order(string Id, string CustomerEmail, Customer Customer);
record Customer(bool PhoneVerified, string Phone);

Tip

Tip

Practice DI Container Service Lifetimes Deep Dive in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of DI Container Service Lifetimes Deep Dive from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with DI Container Service Lifetimes Deep Dive is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done