question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Question regarding IPipelineBehavior

See original GitHub issue

Hi, I’m trying to use the IPipelineBehavior in a very specific way and (probably - likely - very much) I’m missing something because it is not working.

All my requests are of type IRequest<OperationResult> or IRequest<OperationResult<TResult>>. OperationResult is a class that’s basically a way for me to return a (possible) failed result, with errors, and if the result is not failed, a way to attach a value to it (the generic version).

Now, I want to add in a pipeline so I can short-circuit the flow if some condition is met. I then defined my pipeline like this: public sealed class AuthorizationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, OperationResult<TResponse>> where TRequest : class, IRequest<OperationResult<TResponse>> but on execution that throws because TResponse is not the type I want (the result type), but the type of the IResult<T>.

Of course that I can’t define an AuthorizationBehavior<TRequest, OperationResult<TResponse>>. That’s not valid. So, I’m blind right now as I don’t know how to define the pipeline in order for me to be able to short-circuit it, without throwing an exception, and be able to return my own OperationResult<TResponse> inside the handler if I need to…

Any hints or ideas? Maybe I’m using this wrong and I have to do it in another way?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:12 (5 by maintainers)

github_iconTop GitHub Comments

5reactions
jbogardcommented, Nov 18, 2017

Yes! I should blog about this more 😛

On Thu, Nov 16, 2017 at 11:29 AM, Ricardo Peres notifications@github.com wrote:

Not exactly the same, but similar: I want to register an implementation of IPipelineBehavior for a concrete type, like: svcs.AddScoped<IPipelineBehavior<Command, Command>, CommandPipelineBehavior>();

however, the CommandPipelineBehavior class is never resolved! But if I register an open implementation:

svcs.AddScoped<IPipelineBehavior<, >, GenericPipelineBehavior<, >>();

it does! Is this supposed to? Thanks!

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/jbogard/MediatR/issues/201#issuecomment-344997633, or mute the thread https://github.com/notifications/unsubscribe-auth/AAGYMrSDw6ee-syKSxV0SbS5n5PijdbEks5s3HDtgaJpZM4P3BBb .

4reactions
jhoibycommented, Jan 5, 2018

Oops, figured it out finally!

For others to reference, here is how I setup my validation pipeline behavior to return result metadata:

public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
        where TRequest : IRequest<TResponse>
        where TResponse : CommonResult
    {
        private readonly IEnumerable<IValidator<TRequest>> _validators;
        private readonly ILogger _logger;

        public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators, ILogger logger)
        {
            _validators = validators ?? throw new ArgumentNullException(nameof(validators));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        public Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
        {
            var failures = _validators
                .Select(v => v.Validate(request))
                .SelectMany(result => result.Errors)
                .Where(f => f != null)
                .ToList();

            if (failures.Count != 0)
            {
                CommonResult validationResult = new CommonResult(
                    messageId: request.MessageId,
                    outcome: Outcome.MessageValidationFailure,
                    flashMessage: "A validation error occured in request " + typeof(TRequest),
                    errors: failures.ToCommonResultErrorCollection() );

                validationResult.LogErrors(typeof(TRequest), CorrelationId, _logger);

                return Task.FromResult(validationResult as TResponse);
            }

            return next();
        }
    }

Feedback is welcome!

Read more comments on GitHub >

github_iconTop Results From Across the Web

MediatR IPipelineBehavior<TRequest, TResponse> errors ...
I managed to find the porting guide from official MediatR repo. But couldn't find any examples. Am I missing something else, Please can...
Read more >
MediatR Pipeline Behaviour in ASP.NET Core - Logging ...
Let's learn about MediatR Pipeline Behaviour in ASP.NET Core, the idea of Pipelines, How to intersect the pipeline and add various Services like ......
Read more >
Diagnosing and Fixing MediatR Container Issues
We can now focus on fixing this test without worrying about how to test if a handler is called altogether or worrying about...
Read more >
Validation without Exceptions using a MediatR Pipeline ...
The pipeline which I will be showing shortly will need a validator object to invoke, to perform validation on the command which has...
Read more >
CQRS Validation Pipeline with MediatR and FluentValidation
We are going to learn how to implement validation as a cross-cutting concern using CQRS pattern with MediatR and FluentValidation.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found