Pipeline Behaviors
MediatR pipeline behaviors for cross-cutting concerns.
ValidationBehavior
Automatically validates requests using FluentValidation.
How It Works
- Intercepts requests before handler
- Runs all registered IValidator<TRequest>
- Returns Result.Failure if validation fails
- Continues to handler if valid
Registration
csharp
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));Creating Validators
csharp
public class CreateUserCommandValidator : AbstractValidator<CreateUserCommand>
{
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.