Search code examples
.net-coremediatr

How do I register a MediatR post processor


I would like to try the new pipeline feature in MediatR: https://github.com/jbogard/MediatR/wiki/Behaviors

I tried the following, but it does not get executed

services.AddMediatR();                    
services.AddTransient(typeof(IRequestPostProcessor<,>), typeof(PostHandler<,>));

What am I missing?


Solution

  • You need to register the behavior associated with post-processors, like this unit test shows.

    Your registration code would look like:

    services.AddMediatR();
    services.AddTransient(typeof(IRequestPostProcessor<,>), typeof(PostHandler<,>));
    services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPostProcessorBehavior<,>));
    

    That behavior will get all the post-processors you registered and execute them.

    Edit

    After a comment about the post-processor running twice, I had a look at the code that registers MediatR in the ASP.NET Core built-in DI container, and it turns out instances of IRequestPreProcessor<TRequest, TResponse> and IRequestPostProcessor<TRequest, TResponse> are automatically registered as you can see here. What's left to do to get them running in the pipeline is just register the associated behavior. So the necessary registration is then:

    services.AddMediatR();
    services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPostProcessorBehavior<,>));