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.