-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFluentValidationFilter.cs
45 lines (36 loc) · 1.32 KB
/
FluentValidationFilter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
namespace MassTransit;
public class FluentValidationFilter<TMessage> : IFilter<ConsumeContext<TMessage>>
where TMessage : class
{
private readonly IValidationFailurePipe<TMessage> _failurePipe;
private readonly IValidator<TMessage>? _validator;
public FluentValidationFilter(IValidator<TMessage>? validator, IValidationFailurePipe<TMessage> failurePipe)
{
_validator = validator;
_failurePipe = failurePipe ?? throw new ArgumentNullException(nameof(failurePipe));
}
public void Probe(ProbeContext context)
{
context.CreateScope("FluentValidationFilter");
}
public async Task Send(
ConsumeContext<TMessage> context,
IPipe<ConsumeContext<TMessage>> next)
{
if (_validator is null)
{
await next.Send(context);
return;
}
var message = context.Message;
var validationResult = await _validator.ValidateAsync(message, context.CancellationToken);
if (validationResult.IsValid)
{
await next.Send(context);
return;
}
var validationProblems = validationResult.Errors.ToErrorDictionary();
var failureContext = new ValidationFailureContext<TMessage>(context, validationProblems);
await _failurePipe.Send(failureContext);
}
}