using FluentValidation; using MediatR; using ValidationException = ExpenseTracker.Application.Common.Exceptions.ValidationException; namespace ExpenseTracker.Application.Common.Behaviours; public class ValidationBehaviour : IPipelineBehavior where TRequest : notnull { private readonly IEnumerable> _validators; public ValidationBehaviour(IEnumerable> validators) { _validators = validators; } public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) { if (_validators.Any()) { var context = new ValidationContext(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(); } }