Lesson 25 of 40
Architecture
Intermediate
30 min
Configuration & Options Pattern
Master the Options pattern, configuration providers, strongly-typed settings, and hot-reload configuration in .NET 10.
Part 1: Options Pattern
public class SmtpOptions
{
[Required] public string Host { get; init; } = "";
public int Port { get; init; } = 587;
}
// Register
builder.Services.AddOptions<SmtpOptions>()
.BindConfiguration("Smtp").ValidateDataAnnotations();
{
[Required] public string Host { get; init; } = "";
public int Port { get; init; } = 587;
}
// Register
builder.Services.AddOptions<SmtpOptions>()
.BindConfiguration("Smtp").ValidateDataAnnotations();
Part 2: IOptionsMonitor for Hot Reload
// IOptionsSnapshot — per-request (scoped)
// IOptionsMonitor — reacts to config changes (singleton)
public class EmailService(IOptionsMonitor<SmtpOptions> monitor)
{
void Send() => // monitor.CurrentValue always fresh
_smtp.Connect(monitor.CurrentValue.Host);
}
// IOptionsMonitor — reacts to config changes (singleton)
public class EmailService(IOptionsMonitor<SmtpOptions> monitor)
{
void Send() => // monitor.CurrentValue always fresh
_smtp.Connect(monitor.CurrentValue.Host);
}
Part 3: Custom Configuration Providers
Build a config provider that reads from a database or API:
public class DbConfigProvider : ConfigurationProvider
{
public override void Load()
{
var settings = _db.Settings.ToDictionary(s => s.Key, s => s.Value);
Data = settings;
}
}
{
public override void Load()
{
var settings = _db.Settings.ToDictionary(s => s.Key, s => s.Value);
Data = settings;
}
}
Part 4: Environment-Specific Config
| File | Purpose |
|---|---|
| appsettings.json | Base configuration |
| appsettings.Development.json | Local dev overrides |
| appsettings.Production.json | Production overrides |
| User Secrets | Local secrets (never committed) |
| Environment Variables | CI/CD and container config |