When building enterprise applications using CQRS and Clean Architecture, one common trap is scattering validation logic across your controllers, command handlers, or domain entities. This leads to code duplication, inconsistent error responses, and bloated handlers that violate the Single Responsibility Principle.
A much cleaner, more robust approach is to combine FluentValidation with MediatR Pipeline Behaviors. This intercepts incoming requests automatically before they ever reach your command or query handlers, validating rules cleanly and rejecting malformed requests instantly.
In this comprehensive guide, we will walk through setting up FluentValidation with MediatR pipeline behaviors in an ASP.NET Core Clean Architecture project.
Why Use MediatR Pipeline Behaviors for Validation?
MediatR pipeline behaviors act as middleware for your application requests. Instead of manually invoking a validator inside every single command handler, a generic validation behavior intercepts all requests implementing IRequest<T>, runs any registered validators asynchronously, and throws a validation exception if rules fail.
Benefits include:
Separation of Concerns: Handlers focus solely on business logic; validation logic lives entirely in dedicated validator classes.
DRY (Don't Repeat Yourself): Validation happens globally and automatically through the pipeline.
Early Exit: Invalid requests are rejected before hitting the database or executing business logic.
Step 1: Install Required NuGet Packages
Navigate to your Application project (YourSolution.Application) and install FluentValidation along with its dependency injection extensions:
Bash
dotnet add package FluentValidation
dotnet add package FluentValidation.DependencyInjectionExtensions
Step 2: Create a Validator for Your Command
FluentValidation allows you to write strongly-typed, expressive validation rules using AbstractValidator<T>.
Create a validator class for your CreateProductCommand:
C#
using FluentValidation;
using YourSolution.Application.Features.Products.Commands;
namespace YourSolution.Application.Features.Products.Validators
{
public class CreateProductCommandValidator : AbstractValidator<CreateProductCommand>
{
public CreateProductCommandValidator()
{
RuleFor(p => p.Name)
.NotEmpty().WithMessage("Product name is required.")
.MaximumLength(100).WithMessage("Product name cannot exceed 100 characters.");
RuleFor(p => p.Price)
.GreaterThan(0).WithMessage("Product price must be greater than zero.");
}
}
}
Step 3: Implement the MediatR Pipeline Behavior
Next, create a generic pipeline behavior. This class implements MediatR's IPipelineBehavior<TRequest, TResponse> interface. It checks if any validators are registered for the incoming request type, runs them, and collects any failures.
Join the conversation! Your thoughts help the community grow.