Skip to content

Latest commit

 

History

History
88 lines (70 loc) · 3.97 KB

README.md

File metadata and controls

88 lines (70 loc) · 3.97 KB

Build Status Lines of Code Coverage Reliability Rating Security Rating

IL.FluentValidation.Extensions.Options

Microsoft.Extensions.Options validation with FluentValidation.

NuGet

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