38 lines
1.1 KiB
C#
38 lines
1.1 KiB
C#
using FluentValidation;
|
|
using MediatR;
|
|
using ValidationException = ExpenseTracker.Application.Common.Exceptions.ValidationException;
|
|
|
|
namespace ExpenseTracker.Application.Common.Behaviours;
|
|
|
|
public class ValidationBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
|
|
where TRequest : notnull
|
|
{
|
|
private readonly IEnumerable<IValidator<TRequest>> _validators;
|
|
|
|
public ValidationBehaviour(IEnumerable<IValidator<TRequest>> validators)
|
|
{
|
|
_validators = validators;
|
|
}
|
|
|
|
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
|
|
{
|
|
if (_validators.Any())
|
|
{
|
|
var context = new ValidationContext<TRequest>(request);
|
|
|
|
var failures = _validators
|
|
.Select(v => v.Validate(context))
|
|
.SelectMany(r => r.Errors)
|
|
.Where(f => f != null)
|
|
.ToList();
|
|
|
|
if (failures.Any())
|
|
{
|
|
throw new ValidationException(failures);
|
|
}
|
|
}
|
|
|
|
return await next();
|
|
}
|
|
}
|