Created
May 1, 2023 11:20
-
-
Save JayGhb/286734bf744a1220803c3ac96d5436e4 to your computer and use it in GitHub Desktop.
Simple validation behavior using FluentValidation and MediatR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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