dotnet-options-pattern-configuration
Strongly-typed configuration in ASP.NET Core using IOptions, IOptionsSnapshot, IOptionsMonitor, and Named Options β with validation, hot-reload, and change notifications.
π Support the Channel β Join on Patreon
If this sample saved you time, consider joining our Patreon community.
You'll get exclusive .NET tutorials, premium code samples, and early access to new content β all for the price of a coffee.
π Join CodingDroplets on Patreon
Prefer a one-time tip? Buy us a coffee β
π― What You'll Learn
- How the Options Pattern solves raw
IConfiguration access anti-patterns
- The difference between IOptions, IOptionsSnapshot, and IOptionsMonitor β and when to use each
- How to use Named Options to configure multiple independent instances of the same class
- How to add data annotation validation (
[Required], [Range], [EmailAddress]) and fail-fast at startup with ValidateOnStart()
- How to enable hot-reload of configuration without restarting the application
- How to subscribe to runtime change notifications via
IOptionsMonitor.OnChange
- How to unit test each options interface without a running host
πΊοΈ Architecture Overview
appsettings.json / appsettings.Development.json
β
βΌ
IConfiguration (file watcher enabled)
β
ββββ Smtp section βββββββΊ IOptions<SmtpOptions> ββ Singleton (frozen at startup)
β β
β βΌ
β EmailService (Singleton)
β GET /api/smtp
β
ββββ Cache:L1 section βββΊ IOptionsSnapshot<CacheOptions>("L1") β
β ββ Scoped, reloads per request
ββββ Cache:L2 section βββΊ IOptionsSnapshot<CacheOptions>("L2") β
β β
β βΌ
β CacheInfoService (Scoped)
β GET /api/cache | /api/cache/l1 | /api/cache/l2
β
ββββ FeatureFlags section βΊ IOptionsMonitor<FeatureFlagOptions> ββ Singleton + live change events
β
βΌ
FeatureFlagService (Singleton)
GET /api/featureflags | /api/featureflags/{flag}
π Options Interface Comparison
| Interface |
Lifetime |
Picks up config reload? |
When to use |
IOptions<T> |
Singleton |
β Never |
Settings that never change at runtime (DB connection strings, JWT secrets) |
IOptionsSnapshot<T> |
Scoped |
β
Next request |
Per-request settings, named options, feature config that can reload between requests |
IOptionsMonitor<T> |
Singleton |
β
Immediately |
Singleton services needing live config, change event callbacks, feature flags |
IOptionsFactory<T> |
Transient |
β
Always |
Manual resolution; rarely used directly |
π Project Structure
dotnet-options-pattern-configuration/
βββ dotnet-options-pattern-configuration.sln
β
βββ OptionsPatternDemo/ # ASP.NET Core Web API (.NET 10)
β βββ Controllers/
β β βββ SmtpController.cs # GET /api/smtp β IOptions demo
β β βββ CacheController.cs # GET /api/cache β IOptionsSnapshot + Named Options
β β βββ FeatureFlagsController.cs # GET /api/featureflags β IOptionsMonitor demo
β βββ Options/
β β βββ SmtpOptions.cs # Strongly-typed SMTP config with [Required]/[Range]
β β βββ CacheOptions.cs # Cache policy config (L1/L2 named instances)
β β βββ FeatureFlagOptions.cs # Boolean feature flags (hot-reloadable)
β βββ Services/
β β βββ EmailService.cs # Uses IOptions<SmtpOptions>
β β βββ CacheInfoService.cs # Uses IOptionsSnapshot<CacheOptions>
β β βββ FeatureFlagService.cs # Uses IOptionsMonitor<FeatureFlagOptions>
β βββ Properties/
β β βββ launchSettings.json # Swagger opens on launch
β βββ appsettings.json # Production config
β βββ appsettings.Development.json # Dev overrides (hot-reload enabled)
β βββ Program.cs # DI registrations + Swagger setup
β
βββ OptionsPatternDemo.Tests/ # xUnit test project
βββ SmtpOptionsTests.cs # Validation + EmailService unit tests (9 tests)
βββ CacheOptionsTests.cs # Validation + named options tests (5 tests)
βββ FeatureFlagTests.cs # IOptionsMonitor unit tests (2 tests)
π οΈ Prerequisites
| Requirement |
Version |
| .NET SDK |
10.0+ |
| IDE |
Visual Studio 2022 v17.12+ / JetBrains Rider / VS Code |
| OS |
Windows / macOS / Linux |
β‘ Quick Start
# 1. Clone the repository
git clone https://github.com/codingdroplets/dotnet-options-pattern-configuration.git
cd dotnet-options-pattern-configuration
# 2. Build the solution
dotnet build -c Release
# 3. Run the API
cd OptionsPatternDemo
dotnet run
# 4. Open Swagger UI
# http://localhost:5289/swagger
Visual Studio users: press F5 β the browser will open automatically at /swagger.
π§ How It Works
1. Define a strongly-typed options class
public sealed class SmtpOptions
{
public const string SectionName = "Smtp";
[Required] public string Host { get; set; } = string.Empty;
[Range(1, 65535)] public int Port { get; set; } = 587;
[Required][EmailAddress] public string SenderEmail { get; set; } = string.Empty;
public bool EnableSsl { get; set; } = true;
}
2. Bind and validate in Program.cs
builder.Services
.AddOptions<SmtpOptions>()
.Bind(builder.Configuration.GetSection(SmtpOptions.SectionName))
.ValidateDataAnnotations() // Validates [Required], [Range], [EmailAddress] etc.
.ValidateOnStart(); // Fails fast at startup β not lazily on first use
3. Use IOptions<T> in a Singleton service (frozen at startup)
public sealed class EmailService : IEmailService
{
private readonly SmtpOptions _smtp;
public EmailService(IOptions<SmtpOptions> options)
{
_smtp = options.Value; // Captured once β never changes
}
}
4. Use Named Options + IOptionsSnapshot<T> in a Scoped service
// Register two named instances
builder.Services.AddOptions<CacheOptions>("L1")
.Bind(builder.Configuration.GetSection("Cache:L1"));
builder.Services.AddOptions<CacheOptions>("L2")
.Bind(builder.Configuration.GetSection("Cache:L2"));
// Consume in a Scoped service
public sealed class CacheInfoService : ICacheInfoService
{
private readonly IOptionsSnapshot<CacheOptions> _cacheOptions;
public CacheInfoService(IOptionsSnapshot<CacheOptions> cacheOptions)
{
_cacheOptions = cacheOptions;
}
public CachePolicyInfo GetCachePolicy(string name)
{
var opts = _cacheOptions.Get(name); // "L1" or "L2"
return new CachePolicyInfo(name, opts.Provider, opts.DefaultTtlSeconds, opts.Enabled, opts.MaxItems);
}
}
5. Use IOptionsMonitor<T> for live reload in a Singleton
public sealed class FeatureFlagService : IFeatureFlagService, IDisposable
{
private readonly IOptionsMonitor<FeatureFlagOptions> _monitor;
private readonly IDisposable? _changeListener;
public FeatureFlagService(IOptionsMonitor<FeatureFlagOptions> monitor, ILogger<FeatureFlagService> logger)
{
_monitor = monitor;
// Fires whenever appsettings.json changes on disk
_changeListener = _monitor.OnChange((opts, _) =>
logger.LogInformation("Feature flags reloaded: BetaApi={BetaApi}", opts.EnableBetaApi));
}
public FeatureFlagSnapshot GetFlags()
{
var flags = _monitor.CurrentValue; // Always latest config β no restart needed
return new FeatureFlagSnapshot(flags.EnableDarkMode, flags.EnableBetaApi, flags.EnableAnalytics, flags.EnableNewDashboard);
}
public void Dispose() => _changeListener?.Dispose();
}
π‘ API Endpoints
| Method |
Endpoint |
Description |
Status |
GET |
/api/smtp |
Returns SMTP config via IOptions<T> (singleton snapshot) |
200 OK |
GET |
/api/cache |
Returns both L1 + L2 cache policies |
200 OK |
GET |
/api/cache/l1 |
Returns L1 (InMemory) cache policy via named options |
200 OK |
GET |
/api/cache/l2 |
Returns L2 (Redis) cache policy via named options |
200 OK |
GET |
/api/featureflags |
Returns all feature flags via IOptionsMonitor<T> |
200 OK |
GET |
/api/featureflags/{flag} |
Returns a single feature flag by name |
200 OK / 404 Not Found |
π§ͺ Running Tests
dotnet test -c Release
| Test Class |
Tests |
What's Covered |
SmtpOptionsTests |
9 |
Valid config passes, missing Host fails, invalid email fails, port boundary validation, EmailService unit test |
CacheOptionsTests |
5 |
Valid config passes, missing Provider fails, TTL boundary validation, L1/L2 named options resolution |
FeatureFlagTests |
2 |
All flags disabled, all flags enabled β IOptionsMonitor with fake monitor |
| Total |
16 |
All passing β
|
π€ Key Concepts
Why not just use IConfiguration directly?
// β Anti-pattern β magic strings, no type safety, no validation
var host = _configuration["Smtp:Host"];
var port = int.Parse(_configuration["Smtp:Port"]!);
// β
Options Pattern β strongly typed, validated, testable
var host = _smtp.Host;
var port = _smtp.Port;
ValidateOnStart vs lazy validation
By default, options are validated the first time .Value is accessed. ValidateOnStart() moves that check to app startup so misconfiguration is caught immediately β before any request is served.
Why IOptionsSnapshot cannot be injected into Singletons
IOptionsSnapshot<T> is registered as Scoped. Injecting a Scoped dependency into a Singleton creates a captive dependency β the snapshot is frozen at the time the Singleton is first resolved and will never update.
| Service Lifetime |
Compatible Interfaces |
| Singleton |
IOptions<T>, IOptionsMonitor<T> |
| Scoped |
IOptions<T>, IOptionsSnapshot<T>, IOptionsMonitor<T> |
| Transient |
All |
π·οΈ Technologies Used
- .NET 10 β target framework
- ASP.NET Core Web API β controller-based REST API
- Microsoft.Extensions.Options β IOptions / IOptionsSnapshot / IOptionsMonitor
- Swashbuckle.AspNetCore 6.x β Swagger / OpenAPI documentation
- Data Annotations β
[Required], [Range], [EmailAddress] for options validation
- xUnit β unit testing framework
- Microsoft.Extensions.Options.DataAnnotations β
ValidateDataAnnotations() + ValidateOnStart()
π References
π License
This project is licensed under the MIT License. See LICENSE for details.
π Connect with CodingDroplets
Want more samples like this?