In this post I described the problem that by default, DataAnnotation validation doesn't recursively inspect all properties in an object for DataAnnotation attributes. There are several solutions to this problem, but in this post I used the MiniValidation library from Damian Edwards. This simple library provides a convenience wrapper around DataAnnotation validation, as well as providing features like recursive validation. Finally I showed how you can replace the built-in DataAnnotation validation with a MiniValidation-based validator
var builder = WebApplication.CreateBuilder(args); builder.Services.AddOptions<MySettings>() .BindConfiguration("MySettings") .ValidateMiniValidation() // 👈 Replace with mini validation .ValidateOnStart(); var app = builder.Build();
OptionsValidationException: DataAnnotation validation failed for 'MySettings' member: 'Nested.Value' with errors: 'The Value field is required.'.; DataAnnotation validation failed for 'MySettings' member: 'Nested.Count' with errors: 'The field Count must be between 1 and 100.'. Microsoft.Extensions.Options.OptionsFactory<TOptions>.Create(string name) Microsoft.Extensions.Options.OptionsMonitor<TOptions>+<>c__DisplayClass10_0.<Get>b__0()