Created
October 31, 2019 15:17
-
-
Save ielcoro/3533abe287313663c100c5e6524e4df3 to your computer and use it in GitHub Desktop.
FluentValidation integration with Mediatr sample
This file contains 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
using MediatR; | |
using System.Reflection; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace FrameworkExtensions.MediatR.Validation | |
{ | |
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> | |
where TResponse : IRequestResponse | |
{ | |
private readonly PropertyInfo validationProperty; | |
private readonly ValidatorCollection validators; | |
public ValidationBehavior(ValidatorCollection validators) | |
{ | |
this.validators = validators; | |
var validateAttribute = typeof(TRequest).GetCustomAttribute<ValidateAttribute>(); | |
if (validateAttribute == null) | |
return; | |
validationProperty = typeof(TRequest).GetProperty(validateAttribute.PropertyName); | |
} | |
public async Task<TResponse> Handle( | |
TRequest request, | |
CancellationToken cancellationToken, | |
RequestHandlerDelegate<TResponse> next) | |
{ | |
if (validationProperty == null) | |
return await next(); | |
var validator = validators.GetValidatorFor(validationProperty.PropertyType); | |
var validationResult = await validator.ValidateAsync(validationProperty.GetValue(request, null), cancellationToken); | |
if (!validationResult.IsValid) | |
return RequestResponse.OfType<TResponse>(nameof(RequestResponse.NotOk), validationResult); | |
var response = await next(); | |
response.ValidationResult = validationResult; | |
return response; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment