Skip to content

Instantly share code, notes, and snippets.

@ielcoro
Created October 31, 2019 15:17
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 ielcoro/3533abe287313663c100c5e6524e4df3 to your computer and use it in GitHub Desktop.
Save ielcoro/3533abe287313663c100c5e6524e4df3 to your computer and use it in GitHub Desktop.
FluentValidation integration with Mediatr sample
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