Middleman.FluentValidation 1.0.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package Middleman.FluentValidation --version 1.0.2
                    
NuGet\Install-Package Middleman.FluentValidation -Version 1.0.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Middleman.FluentValidation" Version="1.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Middleman.FluentValidation" Version="1.0.2" />
                    
Directory.Packages.props
<PackageReference Include="Middleman.FluentValidation" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Middleman.FluentValidation --version 1.0.2
                    
#r "nuget: Middleman.FluentValidation, 1.0.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Middleman.FluentValidation@1.0.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Middleman.FluentValidation&version=1.0.2
                    
Install as a Cake Addin
#tool nuget:?package=Middleman.FluentValidation&version=1.0.2
                    
Install as a Cake Tool

Middleman.FluentValidation 🛡️✨

License: MIT

The official extension to integrate FluentValidation into your Middleman request and notification pipeline. Ensure your requests and queries are always validated before being processed by their respective handlers.

Overview

Middleman.FluentValidation provides IPipelineBehavior implementations that intercept IRequest and IRequest<TResponse> dispatched through IMiddleman. It automatically locates and executes all registered FluentValidation validators (AbstractValidator<TRequest>) for the given request. If any validation rule fails, a FluentValidation.ValidationException is thrown, preventing the request from reaching its handler.

This library is essential for implementing robust and decoupled validation within your Middleman-based architecture.

Installation

The easiest way to add Middleman.FluentValidation to your project is via the NuGet Package Manager.

dotnet add package Middleman.FluentValidation

You will also need to have Middleman and FluentValidation.DependencyInjectionExtensions installed in your application project:

dotnet add package Middleman
dotnet add package FluentValidation.DependencyInjectionExtensions

Configuration

Configure Middleman.FluentValidation in your Program.cs (or Startup.cs for .NET Framework) alongside the registration of Middleman and your validators.

using System.Reflection;
using FluentValidation;
using Middleman; // For AddMiddleman
using Middleman.FluentValidation; // For AddMiddlemanFluentValidation

var builder = WebApplication.CreateBuilder(args);

// ... other services

// 1. Register Middleman and all its handlers within the current assembly
builder.Services.AddMiddleman(Assembly.GetExecutingAssembly());

// 2. Add the Validation Pipeline Behavior to Middleman
//    This ensures all requests will go through validation
builder.Services.AddMiddlemanFluentValidation(Assembly.GetExecutingAssembly());

// ... rest of your application setup and build

Example Usage

1. Define Your Requests and Validators

Create your requests (with or without a return value) and their respective validators inheriting from AbstractValidator<TRequest>.

// Request with a return value
public class CreateUserRequest : IRequest<Guid>
{
    public string UserName { get; }
    public string Email { get; }
    public CreateUserRequest(string userName, string email) { UserName = userName; Email = email; }
}

// Validator for CreateUserRequest
public class CreateUserRequestValidator : AbstractValidator<CreateUserRequest>
{
    public CreateUserRequestValidator()
    {
        RuleFor(x => x.UserName)
            .NotEmpty().WithMessage("User name is required.")
            .MinimumLength(3).WithMessage("User name must be at least 3 characters long.");

        RuleFor(x => x.Email)
            .NotEmpty().WithMessage("Email is required.")
            .EmailAddress().WithMessage("Invalid email format.");
    }
}

// Request without a return value
public class DeleteUserRequest : IRequest
{
    public Guid UserId { get; }
    public DeleteUserRequest(Guid userId) => UserId = userId;
}

// Validator for DeleteUserRequest
public class DeleteUserRequestValidator : AbstractValidator<DeleteUserRequest>
{
    public DeleteUserRequestValidator()
    {
        RuleFor(x => x.UserId).NotEmpty().WithMessage("User ID cannot be empty.");
    }
}

2. Dispatch Your Requests via IMiddleman

In your application logic (e.g., in an API Controller), inject IMiddleman and dispatch your requests. Validation will be executed automatically.

using Microsoft.AspNetCore.Mvc;
using Middleman.Abstractions;
using FluentValidation; // To catch ValidationException
using System.Linq; // For Select extension method

[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
    private readonly IMiddleman _middleman;

    public UsersController(IMiddleman middleman)
    {
        _middleman = middleman;
    }

    [HttpPost]
    public async Task<IActionResult> CreateUser([FromBody] CreateUserDto dto)
    {
        var request = new CreateUserRequest(dto.UserName, dto.Email);
        try
        {
            var newUserId = await _middleman.Send(request); // Validation occurs here!
            return Ok(new { Id = newUserId });
        }
        catch (ValidationException ex)
        {
            // Catch validation failures and return a Bad Request
            return BadRequest(ex.Errors.Select(e => new { Field = e.PropertyName, Message = e.ErrorMessage }));
        }
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteUser(Guid id)
    {
        var request = new DeleteUserRequest(id);
        try
        {
            await _middleman.Send(request); // Validation occurs here!
            return NoContent();
        }
        catch (ValidationException ex)
        {
            return BadRequest(ex.Errors.Select(e => new { Field = e.PropertyName, Message = e.ErrorMessage }));
        }
    }
}

How It Works (Internally)

Middleman.FluentValidation registers two distinct IPipelineBehavior implementations:

  • ValidationBehavior<TRequest, TResponse>: Used for requests that implement IRequest<TResponse>.
  • ValidationBehaviorNoResult<TRequest>: Used for requests that implement only IRequest.

Both behaviors intercept the request, resolve all IValidator<TRequest> for that specific request from the DI container, and execute them. If any failures are found, a ValidationException is thrown, halting the pipeline's execution.

Contributing

Contributions are welcome! If you find a bug or have a suggestion for an improvement, feel free to open an issue or submit a Pull Request.

License

This project is licensed under the MIT License. See the LICENSE file for more details.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.4 103 4/10/2026
1.0.3 95 4/10/2026
1.0.2 100 4/10/2026
1.0.1 97 4/10/2026
1.0.0 106 3/29/2026