How to validate options on start in C#
Options validation in C# is a way to ensure that the options provided to a program are valid and meet certain criteria before the program starts running.
Adding option validation to services configuration
Given a simple options class:
public class MyOptions
{
public const string SectionName = "MyOptions";
[Required]
public string Name { get; set; }
public int Age { get; set; }
}You can add validation to the options in the ConfigureServices method of your Startup class:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions<MyOptions>()
.BindConfiguration(MyOptions.SectionName)
.ValidateDataAnnotations()
.ValidateOnStart();
}In the example above, we are using the ValidateDataAnnotations method to validate the properties of the MyOptions class using data annotations.
The ValidateOnStart method ensures that the validation is performed when the application starts.
This way, if the options are not valid, an exception will be thrown, and the application will not start.
ValidateOnStart was introduced in .NET 6 — without it, an options class is only validated the first time it's actually resolved (e.g. the first time it's injected into a constructor), which means an invalid configuration could go unnoticed until that code path runs in production. Validating on start fails fast instead, at application startup.
This also works the same way with the minimal hosting model, if you're not using a Startup class:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOptions<MyOptions>()
.BindConfiguration(MyOptions.SectionName)
.ValidateDataAnnotations()
.ValidateOnStart();