FluentValidation integrate with Microsoft.Extensions
Microsoft.Extensions.Options validation with FluentValidation.
public class MyOptionsValidator : AbstractValidator<MyOptions> {
// ...
}
using IL.FluentValidation.Extensions.Options;
// Registration
services.AddOptions<MyOptions>("optionalOptionsName")
.Configure(o => { })
.Validate<MyOptions, MyOptionsValidator>(); // ❗ Register validator type
// Consumption
var monitor = services.BuildServiceProvider()
.GetService<IOptionsMonitor<MyOptions>>();
try
{
var options = monitor.Get("optionalOptionsName");
}
catch (OptionsValidationException ex)
{
}
Support multiple way to register validator:
IValidator<MyOptions> validator = new MyOptionsValidator();
services.AddOptions<MyOptions>("optionalOptionsName")
.Configure(o => { })
.Validate(validator); // ❗ Register a validator instance
IValidator<MyOptions> validator = new MyOptionsValidator();
services.AddTransient<IValidator<MyOptions>, MyOptionsValidator>();
services.AddOptions<MyOptions>("optionalOptionsName")
.Configure(o => { })
.Validate(serviceProvider => serviceProvider.GetRequiredService<IValidator<MyOptions>>()); // ❗ Register a validator creator function
If you have already registered an IValidator<T>
in the service container (e.g. using FluentValidation.DependencyInjectionExtensions):
services.AddValidatorsFromAssembly(assembly);
services.AddOptions<MyOptions>("optionalOptionsName")
.Configure(o => { })
.ValidateWithFluentValidator(); // ❗ Register IValidator<MyOptions>
And your favorite fluent style:
IValidator<MyOptions> validator = new MyOptionsValidator();
services.AddOptions<MyOptions>("optionalOptionsName")
.Configure(o => { })
.FluentValidate().With<MyOptionsValidator>(); // ❗ Register a validator type
IValidator<MyOptions> validator = new MyOptionsValidator();
services.AddOptions<MyOptions>("optionalOptionsName")
.Configure(o => { })
.FluentValidate().With(validator); // ❗ Register a validator instance
IValidator<MyOptions> validator = new MyOptionsValidator();
services.AddTransient<IValidator<MyOptions>, MyOptionsValidator>();
services.AddOptions<MyOptions>("optionalOptionsName")
.Configure(o => { })
.FluentValidate().With(serviceProvider => serviceProvider.GetRequiredService<IValidator<MyOptions>>()); // ❗ Register a validator creator function