Skip to content

Pipeline Behaviors

MediatR pipeline behaviors for cross-cutting concerns.

ValidationBehavior

Automatically validates requests using FluentValidation.

How It Works

  1. Intercepts requests before handler
  2. Runs all registered IValidator<TRequest>
  3. Returns Result.Failure if validation fails
  4. Continues to handler if valid

Registration

csharp
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));

Creating Validators

csharp
public class CreateUserCommandValidator : AbstractValidator&lt;CreateUserCommand&gt;
{
    public CreateUserCommandValidator()
    {
        RuleFor(x => x.Email)
            .NotEmpty()
            .EmailAddress();

        RuleFor(x => x.Name)
            .NotEmpty()
            .MaximumLength(100);
    }
}

Response Handling

The behavior automatically returns:

  • Result<T>.Failure with validation errors
  • Result.Failure for non-generic Result
  • ValidationException for other response types

Error Code

All validation failures include error code VALIDATION_ERROR.

Released under the MIT License.