Options Validation & Named Options
Validate options at startup with DataAnnotations or FluentValidation, and use named options for multiple instances.
Why Validate Options?
Missing or malformed configuration causes runtime errors that are hard to trace. Validating options at startup turns silent config bugs into loud, descriptive exceptions before any request is served.
ValidateOnStart
ValidateOnStart() triggers validation immediately when the app starts, not lazily on first use. This means a misconfigured deployment fails instantly rather than hours later.
builder.Services
.AddOptions<DatabaseOptions>()
.BindConfiguration("Database")
.ValidateDataAnnotations()
.ValidateOnStart(); // throw OptionsValidationException on startup
// Without ValidateOnStart:
// - Validation only runs on first IOptions<T>.Value access
// - A rarely-used service could run for hours before failing
// With ValidateOnStart:
// - App fails at Host.Run() if config is invalid
// - Health checks and probes never report healthy for bad configAll lessons in this course
- Configuration Sources & Providers
- Strongly Typed Options with IOptions
- Options Validation & Named Options
- Secrets Management