Created
October 30, 2019 10:23
-
-
Save haamond/1622bddf9a7c6879acf5a07e6a2257d9 to your computer and use it in GitHub Desktop.
Async FluentValidation MediatR Behavior
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
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to use it:
serviceCollection.AddScoped(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));