With MediatR, how do you write a validation behaviour that runs every FluentValidation IValidator<TRequest> before the handler, and what are its traps?
answer
- IEnumerable<IValidator<TRequest>> injected
- ValidateAsync each, collect Errors
- throw ValidationException before next
- IRequest<TResponse> constraint skips void commands
- map to a 400 at the HTTP edge
basics
~20 sA ValidationBehavior<TRequest, TResponse> injects IEnumerable<IValidator<TRequest>>, runs each validator's ValidateAsync before calling next, and throws FluentValidation's ValidationException when any failure exists, so handlers only see valid requests. The web layer turns that exception into a 400.
solid answer
~40 sThe behaviour takes `IEnumerable<IValidator<TRequest>> validators`, awaits `ValidateAsync(request, cancellationToken)` on each, collects `result.Errors`, and throws `new ValidationException(failures)` if any exist; otherwise it returns `await next(cancellationToken)`. Register it with `cfg.AddOpenBehavior(typeof(ValidationBehavior<,>))`, inside logging and outside the transaction. Traps: a request with no validator gets an empty sequence, so the behaviour must just call `next`; a constraint `where TRequest : IRequest<TResponse>` silently skips void commands, because the container drops an open generic whose constraints fail when building the behaviour list, so constrain on `notnull`; validators sharing the request's `DbContext` should run one after another, not with `Task.WhenAll`; and the behaviour cannot return an HTTP result for an arbitrary `TResponse`, so an `IExceptionHandler` or the endpoint maps the exception to a validation ProblemDetails.
code
csharp · 8 linesbuilder.Services.AddValidatorsFromAssemblyContaining<RecordRentPaymentValidator>();
builder.Services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblyContaining<RecordRentPaymentHandler>();
cfg.AddOpenBehavior(typeof(LoggingBehavior<,>));
cfg.AddOpenBehavior(typeof(ValidationBehavior<,>));
cfg.AddOpenBehavior(typeof(TransactionBehavior<,>));
});go deeper
Recall that a validation behaviour runs the request's validators before the handler and throws when any rule fails, so the handler only receives valid commands.
Explain the implementation details: IEnumerable of validators, ValidateAsync, collecting failures, the empty case, and why the behaviour sits inside logging and outside the transaction.
Spot the traps: constraints that silently skip void commands, DbContext concurrency between validators, double validation with endpoint checks, and keeping HTTP mapping at the edge.
Decide where validation is owned across the system: endpoint, command pipeline or domain, and whether failures travel as exceptions or results, then apply it consistently.
## What the behaviour is for FluentValidation validators (`AbstractValidator<RecordRentPayment>` and friends) describe what a valid command looks like; how to write those rules belongs to FluentValidation itself. The MediatR **validation behaviour** is the glue that runs them *for every request sent through the mediator*, whoever sends it: the API endpoint, a nightly job that sends `RecordLateFee`, or a message consumer. The handler can then assume its input is valid. ## The implementation ```csharp public sealed class ValidationBehavior<TRequest, TResponse>( IEnumerable<IValidator<TRequest>> validators) : IPipelineBehavior<TRequest, TResponse> where TRequest : notnull { public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken) { var failures = new List<ValidationFailure>(); foreach (var validator in validators) { var result = await validator.ValidateAsync(request, cancellationToken); failures.AddRange(result.Errors); } if (failures.Count > 0) throw new ValidationException(failures); return await next(cancellationToken); } } ``` Key points: - **`IEnumerable<IValidator<TRequest>>`**, not `IValidator<TRequest>`: a request may have zero, one or several validators, and with none registered the container hands over an empty sequence instead of failing. With zero validators the loop does nothing and the request goes straight on. - **`ValidateAsync`**, not `Validate`: rules that hit the database (is this lease active?) are async, and the synchronous `Validate` throws `AsyncValidatorInvokedSynchronouslyException` when it meets one. - **Sequential loop**: validators resolved in the request scope share its `DbContext`, which does not allow concurrent operations, so `Task.WhenAll` over validators invites an `InvalidOperationException`. - **`ValidationException(IEnumerable<ValidationFailure>)`** carries every failure; each has a `PropertyName` and an `ErrorMessage` the web layer can group. ## The constraint trap Many samples declare `where TRequest : IRequest<TResponse>`. For a command with no result, such as `ArchiveProperty : IRequest`, MediatR resolves `IPipelineBehavior<ArchiveProperty, Unit>`, and `ArchiveProperty` does not implement `IRequest<Unit>`. When the container builds the list of behaviours, it **skips an open generic whose constraints are not satisfied**, silently. The behaviour simply never runs for void commands, and nothing logs why. Use `where TRequest : notnull` (what `IPipelineBehavior` itself requires) or MediatR's `IBaseRequest`, which both request shapes implement. ## Exception or result? | Approach | Behaviour returns | Who turns it into HTTP | |---|---|---| | Throw `ValidationException` | nothing, it throws before `next` | an `IExceptionHandler` or the endpoint writes a 400 validation ProblemDetails | | Return a failed `Result<T>` (your own type) | a failure value without calling `next` | the endpoint maps the result to a 400 | The result approach needs a behaviour declared as `ValidationBehavior<TRequest, T> : IPipelineBehavior<TRequest, Result<T>>`. The container cannot close that shape from `IPipelineBehavior<,>` on its own; MediatR 14.2's `AddOpenBehavior` detects a response type that is itself generic and registers closed versions for every matching request type it finds in the scanned assemblies. A request type outside those assemblies is not covered. ## Where it sits in the pipeline - **Inside logging**, so rejected commands are logged and timed. - **Outside the transaction**, so invalid commands never open one. - **Inside MediatR's exception behaviours**, so an `IRequestExceptionHandler` registered for `ValidationException` would see it. That is rarely what a web API wants. ## Traps that show up in review 1. **Double validation.** If the endpoint already validates its parameters, the same rules run twice; decide which layer owns which checks. 2. **Validator lifetime.** FluentValidation's assembly registration defaults to scoped validators; a validator that depends on a scoped `DbContext` must not be made singleton. 3. **HTTP in the behaviour.** Returning `TypedResults.BadRequest` only compiles when `TResponse` happens to be an `IResult`; it couples the command pipeline to HTTP and breaks the job and consumer callers. 4. **Silent skips.** Test that the behaviour actually runs for a void command and for a command with a result. ## Pinning it down in tests Two tests cover most of the risk. A unit test constructs `ValidationBehavior<RecordRentPayment, PaymentReceipt>` with a real validator and a `next` lambda that records whether it ran: for an invalid amount it must throw `ValidationException` and never call `next`; for a valid one it must call `next` once. An integration test sends an invalid `ArchiveProperty` (a void command) through a mediator built from the application's real registration and expects the same exception, which proves the constraint and the registration, not just the class.
- Your validation behaviour runs for RecordRentPayment but never for ArchiveProperty : IRequest. Why?The behaviour is declared `where TRequest : IRequest<TResponse>`. For a void request MediatR resolves `IPipelineBehavior<ArchiveProperty, Unit>`, and `ArchiveProperty` does not implement `IRequest<Unit>`, so the container silently leaves that open generic out of the behaviour list. Constrain on `notnull` or `IBaseRequest` instead.
- How would a MediatR 14.2 validation behaviour return a failed Result<T> instead of throwing?Declare it as `ValidationBehavior<TRequest, T> : IPipelineBehavior<TRequest, Result<T>>` and return the failure without calling `next`. The container cannot close that nested-generic shape itself; `AddOpenBehavior` detects it and registers closed versions for each matching request type in the scanned assemblies, so requests defined elsewhere are not covered.
- Where should the ValidationException become an HTTP 400?At the ASP.NET Core edge, not in MediatR: an `IExceptionHandler` (or the endpoint) catches FluentValidation's `ValidationException` and writes a validation ProblemDetails, for example with `TypedResults.ValidationProblem` keyed by each failure's `PropertyName`. The behaviour stays HTTP-free, so the same command validates identically when a background job sends it.
- MediatR validates requests automatically once FluentValidation is installed.
- A behaviour constrained to IRequest<TResponse> also wraps void commands.
- With no validator registered, the behaviour fails to resolve IValidator<TRequest>.
- A validation behaviour can return TypedResults.BadRequest for any request type.
- Running all validators with Task.WhenAll is always safe.