⚙️ Options Pattern = Configuration
Configuration is essential. Options Pattern binds configuration to objects. Strongly typed, easy to use.
📝 Options Setup
// appsettings.json
{
"AppSettings": {
"ApiKey": "abc-123-xyz",
"Timeout": 30,
"RetryCount": 3,
"EnableLogging": true,
"BaseUrl": "https://api.example.com"
}
}
// Options class
public class AppSettings
{
public string ApiKey { get; set; }
public int Timeout { get; set; }
public int RetryCount { get; set; }
public bool EnableLogging { get; set; }
public string BaseUrl { get; set; }
}
// Register options
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure(
builder.Configuration.GetSection("AppSettings"));
// Use options (IOptions)
public class MyService
{
private readonly AppSettings _settings;
public MyService(IOptions options)
{
_settings = options.Value;
}
}
🎯 Options Lifecycle
// IOptions (Singleton - cached)
public class Service1
{
public Service1(IOptions options)
{
// Cached, doesn't update on config change
}
}
// IOptionsSnapshot (Scoped - updated)
public class Service2
{
public Service2(IOptionsSnapshot options)
{
// Updated when config changes
}
}
// IOptionsMonitor (Singleton - can detect changes)
public class Service3
{
private readonly IOptionsMonitor _monitor;
public Service3(IOptionsMonitor monitor)
{
_monitor = monitor;
_monitor.OnChange(settings => {
Console.WriteLine("Config changed!");
});
}
}
// Validation
public class AppSettings
{
public string ApiKey { get; set; }
public int Timeout { get; set; }
public void Validate()
{
if (string.IsNullOrEmpty(ApiKey))
throw new Exception("ApiKey is required");
if (Timeout < 1 || Timeout > 60)
throw new Exception("Timeout must be between 1 and 60");
}
}
// Options Tips
- Use IOptions for static config
- Use IOptionsSnapshot for dynamic config
- Use IOptionsMonitor for change detection
- Validate configuration
- Use nested options for complex config
💡 Options Tips
- Use IOptions for static config
- Use IOptionsSnapshot for dynamic config
- Use IOptionsMonitor for change detection
- Validate configuration
- Use nested options for complex config
“Options Pattern simplifies configuration. Strongly typed, easy to use. Essential for .NET apps.”
