Middleman.FluentValidation
1.0.2
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
<PackageReference Include="Middleman.FluentValidation" Version="1.0.2" />
<PackageVersion Include="Middleman.FluentValidation" Version="1.0.2" />
<PackageReference Include="Middleman.FluentValidation" />
paket add Middleman.FluentValidation --version 1.0.2
#r "nuget: Middleman.FluentValidation, 1.0.2"
#:package Middleman.FluentValidation@1.0.2
#addin nuget:?package=Middleman.FluentValidation&version=1.0.2
#tool nuget:?package=Middleman.FluentValidation&version=1.0.2
Middleman.FluentValidation 🛡️✨
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 implementIRequest<TResponse>.ValidationBehaviorNoResult<TRequest>: Used for requests that implement onlyIRequest.
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 | Versions 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. |
-
net9.0
- FluentValidation (>= 12.0.0)
- FluentValidation.DependencyInjectionExtensions (>= 12.0.0)
- Middleman (>= 1.0.2)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.