Using the options validation source generator
.NET 8 introduces the options validation source generator, which generates the validation code based on data annotations. The idea is similar to the configuration-binding source generator but for the validation code.
To leverage the validation generator, we must add a reference on the Microsoft.Extensions.Options.DataAnnotations package.
Afterward, we must:
- Create an empty validator class.
- Ensure the class is
partial. - Implement the
IValidateOptions<TOptions>interface (but not the methods). - Decorate the validator class with the
[OptionsValidator]attribute. - Register the validator class with the container.
This procedure sounds complicated but is way simpler in code; let’s look at that now.
The name of the project in the source code is ConfigurationGenerators.
In this second part of the project, we continue to build on the previous pieces and add validation...