Validating options using FluentValidation
In this project, we validate options classes using FluentValidation. FluentValidation is a popular open-source library that provides a validation framework different from data annotations. One of the primary advantages of FluentValidation is that it allows encapsulating validation rules in another class than the one being validated. That makes the validation logic easier to test and more explicit than depending on metadata added by attributes. We explore FluentValidation more in Chapter 17, Getting Started with Vertical Slice Architecture, but that should not hinder you from following this example.
The name of the project in the source code is OptionsValidationFluentValidation
.
Here, I want to show you how to leverage a few patterns we’ve learned so far to implement this ourselves with only a few lines of code. In this micro-project, we leverage:
- Dependency injection
- The Strategy design pattern
- The Options pattern
- Options validation: Validation types
- Options validation: Eager validation
Let’s start with the options class itself:
public class MyOptions
{
public string? Name { get; set; }
}
The options class is very thin, containing only a nullable Name
property. Next, let’s look at the FluentValidation validator, which validates that the Name
property is not empty:
public class MyOptionsValidator : AbstractValidator<MyOptions>
{
public MyOptionsValidator()
{
RuleFor(x => x.Name).NotEmpty();
}
}
If you have never used FluentValidation before, the AbstractValidator<T>
class implements the IValidator<T>
interface and adds utility methods like RuleFor
. The MyOptionsValidator
class contains the validation rules.
To make ASP.NET Core validate MyOptions
instances using FluentValidation, we must implement an IValidateOptions<TOptions>
interface as we did in the previous example, inject our validator in it, and then leverage it to ensure the validity of MyOptions
objects. This implementation of the IValidateOptions
interface creates a bridge between the FluentValidation features and the ASP.NET Core options validation.
Here is a generic implementation of such a class that could be reused for any type of options:
public class FluentValidateOptions<TOptions> : IValidateOptions<TOptions>
where TOptions : class
{
private readonly IValidator<TOptions> _validator;
public FluentValidateOptions(IValidator<TOptions> validator)
{
_validator = validator;
}
public ValidateOptionsResult Validate(string name, TOptions options)
{
var validationResult = _validator.Validate(options);
if (validationResult.IsValid)
{
return ValidateOptionsResult.Success;
}
var errorMessages = validationResult.Errors.Select(x => x.ErrorMessage);
return ValidateOptionsResult.Fail(errorMessages);
}
}
In the preceding code, the FluentValidateOptions<TOptions>
class adapts the IValidateOptions<TOptions>
interface to the IValidator<TOptions>
interface by leveraging FluentValidation in the Validate
method. In a nutshell, we use the output of one system and make it the input of another system.
This type of adaptation is known as the Adapter design pattern. We explore the Adapter pattern in the next chapter.
Now that we have all the building blocks, let’s have a look at the composition root:
using FluentValidation;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddSingleton<IValidator<MyOptions>, MyOptionsValidator>()
.AddSingleton<IValidateOptions<MyOptions>, FluentValidateOptions<MyOptions>>()
;
builder.Services
.AddOptions<MyOptions>()
.ValidateOnStart()
;
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
The highlighted code is the key to this system:
- It registers the FluentValidation
MyOptionsValidator
that contains the validation rules. - It registers the generic
FluentValidateOptions
instance, so .NET uses it to validate theMyOptions
class. - Under the hood, the
FluentValidateOptions
class uses theMyOptionsValidator
to validate the options internally.
When running the program, the console yields the following error, as expected:
Hosting failed to start
Unhandled exception. Microsoft.Extensions.Options.OptionsValidationException: 'Name' must not be empty.
[...]
This may look like a lot of trouble for a simple required field; however, FluentValidateOptions<TOptions>
is reusable. We could also scan one or more assemblies to register all the validators with the IoC container automatically.
Now that we’ve explored many ways to configure and validate options objects, it is time to look at a way to inject options classes directly, either by choice or to work around a library capability issue.