Skip to content

Instantly share code, notes, and snippets.

@haamond
Created October 30, 2019 10:23
Show Gist options
  • Save haamond/1622bddf9a7c6879acf5a07e6a2257d9 to your computer and use it in GitHub Desktop.
Save haamond/1622bddf9a7c6879acf5a07e6a2257d9 to your computer and use it in GitHub Desktop.
Async FluentValidation MediatR Behavior
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using FluentValidation;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Alamut.MediatR.Behaviors
{
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly ILoggerFactory _loggerFactory;
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidationBehavior(IServiceProvider serviceProvider, ILoggerFactory loggerFactory)
{
_loggerFactory = loggerFactory;
_validators = serviceProvider.GetServices<IValidator<TRequest>>();
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
foreach (var validator in _validators)
{
_loggerFactory
.CreateLogger("ValidationBehavior")
.LogTrace($"ValidationBehavior validate {{{typeof(TRequest).Name}}} with validator {{{validator.GetType().Name}}}");
await validator.ValidateAndThrowAsync<TRequest>(request, cancellationToken: cancellationToken);
}
return await next();
}
}
}
@haamond
Copy link
Author

haamond commented Jun 28, 2021

how to use it:
serviceCollection.AddScoped(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment