Skip to content

Instantly share code, notes, and snippets.

@umayeras
Last active February 23, 2022 06:19
Show Gist options
  • Save umayeras/36ca9bcdd1b62ae675aafaf964f4628a to your computer and use it in GitHub Desktop.
Save umayeras/36ca9bcdd1b62ae675aafaf964f4628a to your computer and use it in GitHub Desktop.
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
where TResponse : ServiceResponse, new()
{
private readonly IEnumerable<IValidator<TRequest>> validators;
public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
{
this.validators = validators;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
if (!validators.Any())
{
return await next.Invoke();
}
var context = new ValidationContext<TRequest>(request);
var results = await Task.WhenAll(validators.Select(v => v.ValidateAsync(context, cancellationToken)));
var failures = results.SelectMany(r => r.Errors).Where(f => f != null).ToList();
if (!failures.Any())
{
return await next.Invoke();
}
var response = CreateValidationErrorResponse(failures);
return await Task.FromResult(response as TResponse);
}
private ValidationErrorResponse CreateValidationErrorResponse(IEnumerable<ValidationFailure> failures)
{
var errors = failures.Select(failure => new ValidationError(failure.PropertyName, failure.ErrorMessage)).ToList();
return ValidationErrorResponse.Create(errors);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment