Skip to content

idarb-oss/Options.FluentValidation

Repository files navigation

Github codecov release pre-release Issues MIT License


Options.FluentValidation

Extensions for Microsoft.Extensions.Options by using FluentValidation to validate your options at runtime.
Explore the docs »

Report Bug · Request Feature

Table of Contents
  1. About The Project
  2. License

About The Project

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();

(back to top)

Built With

(back to top)

How to use

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
    }
}

License

Distributed under the MIT License. See LICENSE for more information.

(back to top)

About

Validation options by using FluentValidation

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages