Свободный ответ MediatR на проверку поведения конвейераC#

Место общения программистов C#
Ответить
Гость
 Свободный ответ MediatR на проверку поведения конвейера

Сообщение Гость »


I have a MediatR Pipeline behavior for validating commands with the FluentValidation library. I've seen many examples where you throw a ValidationException from the behavior, and that works fine for me. However in my scenario I want to update my response object with the validation errors.

I am able to build and run the following code. When I set a break point within the if statement the CommandResponse is constructed with the validation errors as expected - but when the response is received by the original caller it is null:

Код: Выделить всё

public class RequestValidationBehavior : IPipelineBehavior where TRequest : IRequest {     private readonly IEnumerable _validators;     public RequestValidationBehavior(IEnumerable validators)     {          _validators = validators;     }     public Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next)     {         var context = new ValidationContext(request);         // Run the associated validator against the request         var failures = _validators             .Select(v => v.Validate(context))             .SelectMany(result => result.Errors)             .Where(f => f != null)             .ToList();         if(failures.Count != 0)         {             var commandResponse = new CommandResponse(failures) { isSuccess = false };             return commandResponse as Task;         }         else         {                return next();         }     } } 
I think it has to do with my attempt to cast it as Task - but without this I get compiler errors. I'm returning the same type that my command handler would if validation passes so I am at a loss as to why it returns a null instance of the expected response. I feel like there is a better way to handle this, but I've tried a number of variations to no avail. Any suggestions? Is there a better pattern to use? I'd prefer to keep this in the pipeline as it will be reused a lot.


Источник: https://stackoverflow.com/questions/541 ... e-behavior
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»