Provides additional DataAnnotations specific functionality related to Options.
$ dotnet add package Microsoft.Extensions.Options.DataAnnotationsMicrosoft.Extensions.Options.DataAnnotations is a library that adds extra validation functionality to configuration options using data annotations.
It allows to apply validation rules to configuration classes to ensure they are correctly configured before the application starts running.
This way, misconfiguration issues are catched early during the application startup rather than facing them later in production.
While configuring services, chain the ValidateDataAnnotations() and ValidateOnStart() methods to the AddOptions method for your configuration class.
Here is a simple example demonstrating how to validate options on application startup:
services
.AddOptions<MyOptions>()
.ValidateDataAnnotations()
.ValidateOnStart();
In the configuration class, use data annotations to specify the validation rules.
For instance, in the following MyOptions class, the Name property is marked as required:
using System.ComponentModel.DataAnnotations;
public class MyOptions
{
[Required(AllowEmptyStrings = false)]
public string Name { get; set; }
}
With this setup, an error indicating that the Name field is required will be thrown upon startup if it hasn't been configured.
The main types provided by this library are:
Microsoft.Extensions.Options.DataAnnotationsValidateOptions<TOptions>Microsoft.Extensions.DependencyInjection.OptionsBuilderDataAnnotationsExtensionsCore options: Microsoft.Extensions.Options
Microsoft.Extensions.Options.DataAnnotations is released as open source under the MIT license. Bug reports and contributions are welcome at the GitHub repository.