Extensions for Microsoft.Extensions.Options by using FluentValidation to validate your options at runtime.
Explore the docs »
Report Bug
·
Request Feature
Table of Contents
Options.FluentValidation adds extension methods on top of Microsoft.Extensions.Options to be able to use FluentValidation for validating your options.
services.AddOptions<TestOption>()
.Bind(config.GetSection("Options"))
.ValidateFluently();Start by creation your option record:
namespace Options;
public record AppOptions
{
public const string SectionName = "App";
public string Name { get; init; }
public int WorkerCount { get; init; }
}Create an FluentValidation class:
using FluentValidation;
namespace Options;
public class AppOptionsValidation : AbstractValidator<AppOptions>
{
public AppOptionsValidation()
{
RuleFor(o => o.Name)
.NotEmpty()
.NotNull();
RuleFor(o => o.WorkerCount)
.GreaterThan(0)
.LessThan(20);
}
}Then add the option to your IServiceCollection by following:
using Options.FluentValidation;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Options;
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddOptions(this IServiceCollection services, IConfiguration config)
{
services.AddOptions<AppOptions>()
.Bind(config.GetRequiredSection(AppOptions.SectionName))
.ValidateFluently()
.ValidateOnStart(); // Add Microsoft.Extensions.Hosting package
return services;
}
}Then you can add the configuration to your json file or any other means of setting up your configurations.
{
"App": {
"Name": "My fancy app",
"WorkerCount": 15
}
}Distributed under the MIT License. See LICENSE for more information.