Converts options validation to use the compile-time source generator. Use when the user wants AOT-compatible, reflection-free options validation.
Convert options validation to use the compile-time source generator, enabling AOT-compatible, reflection-free validation at startup.
ValidateDataAnnotations() to source-generated validationFind options classes with data annotations:
[Required], [Range], [RegularExpression], [MaxLength], [MinLength], [Length]*Options.cs or *Settings.csCheck existing validation setup:
[OptionsValidator] partial class, skip itValidateDataAnnotations() calls for removal laterFor each options class, create a partial validator class:
[OptionsValidator]
public partial class Validate{OptionsClassName} : IValidateOptions<{OptionsClassName}>
{
}
Register the validator in DI:
services.AddSingleton<IValidateOptions<MyOptions>, ValidateMyOptions>();
ValidateDataAnnotations() callsMicrosoft.Extensions.Options using directive is presentVerify with build:
dotnet build
If build fails, check for:
partial keyword on validator classMicrosoft.Extensions.OptionsReport results:
[Required] - Property must have a value[Range] - Numeric value within specified range[RegularExpression] - String matches regex pattern[MaxLength] - Maximum length for strings/collections[MinLength] - Minimum length for strings/collections[Length] - Exact or range length constraintMicrosoft.Extensions.Options version 8.0 or higherValidateDataAnnotations() is NOT needed and should be removed[OptionsValidator] attribute triggers source generation