DI Lifetimes, Options Pattern & Startup Validation
Part of Module 1: Enterprise Architecture & Solution Structuring
Prevent memory leaks and Captive Dependency bugs, organize DI with layer extensions, and fail fast at startup using ValidateOnStart().
What You Will Master in This Lesson
- Choose accurately between Transient, Scoped, and Singleton lifetimes
- Avoid Captive Dependency bugs when injecting repositories or connections
- Validate strongly-typed appsettings configurations immediately on startup
1. Mastering Dependency Injection Lifetimes
Misconfiguring service lifetimes in Program.cs is one of the fastest ways to trigger subtle memory leaks, stale database state, and cross-request data contamination in ASP.NET Core.
| Lifetime | Created When? | Ideal Enterprise Usage |
|---|---|---|
AddTransient |
Every single time requested | Lightweight, stateless utilities, validators, lightweight mappers |
AddScoped |
Once per HTTP Request | Repositories, DbContext / SQL Connections, Unit of Work, Current User context |
AddSingleton |
Once per Application Lifetime | Configuration caches, MemoryCache, HttpClientFactory wrappers (Must be Thread-Safe!) |
Scoped service (such as a Repository or DbContext) into a Singleton service! The Singleton keeps that Scoped service alive forever across every HTTP user, causing concurrency crashes and connection exhaustion. Enable ValidateScopes in Development (on by default) so .NET catches this immediately.
2. Extension Method Pattern for Clean Registration
Keep Program.cs concise by delegating DI registrations to each architectural layer using extension methods:
// Platform.Infrastructure/DependencyInjection.cs
namespace Platform.Infrastructure;
public static class DependencyInjection
{
public static IServiceCollection AddInfrastructure(
this IServiceCollection services,
IConfiguration configuration)
{
services.AddScoped<ISqlConnectionFactory, SqlConnectionFactory>();
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.AddScoped<IOrderRepository, OrderRepository>();
return services;
}
}
3. Type-Safe Configuration with the Options Pattern & Startup Validation
Never scatter magic string lookups like _config["JwtSettings:SecretKey"] across services. If someone deploys to IIS with a typo in appsettings.Production.json, the app shouldn't crash at 2:00 AM when a user logs in—it should fail fast at startup.
using System.ComponentModel.DataAnnotations;
namespace Platform.Infrastructure.Options;
public sealed class DatabaseOptions
{
public const string SectionName = "DatabaseSettings";
[Required(ErrorMessage = "SqlServer connection string is missing.")]
public string ConnectionString { get; init; } = string.Empty;
[Range(5, 300)]
public int CommandTimeoutSeconds { get; init; } = 30;
}
// Registration in AddInfrastructure():
services.AddOptions<DatabaseOptions>()
.Bind(configuration.GetSection(DatabaseOptions.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart(); // Fails immediately at boot if config is invalid!
4. Choosing IOptions<T> vs IOptionsSnapshot<T> vs IOptionsMonitor<T>
IOptions<T>(Singleton): Reads config once at startup. Fastest, zero reload overhead.IOptionsSnapshot<T>(Scoped): Re-reads changes toappsettings.jsonautomatically per HTTP request without restarting IIS.IOptionsMonitor<T>(Singleton): Supports live reload notifications inside Singletons or BackgroundServices.
Hands-On Lab Exercise
Create a JwtOptions class with [Required] and [MinLength(32)] validation attributes on SecretKey. Wire .ValidateDataAnnotations().ValidateOnStart() in Program.cs, deliberately shorten the secret in appsettings.json, and observe ASP.NET Core throwing an OptionsValidationException immediately on startup.
Knowledge Check
Verify your understanding before advancing to the next lesson:
1. What happens if you inject a Scoped Repository into a Singleton service?
2. Which method forces ASP.NET Core to validate DataAnnotations on Options classes before serving the first request?