Skip to content

Instantly share code, notes, and snippets.

@JayGhb
Created May 1, 2023 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JayGhb/286734bf744a1220803c3ac96d5436e4 to your computer and use it in GitHub Desktop.
Save JayGhb/286734bf744a1220803c3ac96d5436e4 to your computer and use it in GitHub Desktop.
Simple validation behavior using FluentValidation and MediatR
public class ValidatorBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidatorBehavior(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators ?? throw new ArgumentNullException(nameof(validators));
}
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
await Task.WhenAll(_validators.Select(v => v.ValidateAndThrowAsync(request)));
return await next();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment