Wednesday, January 11, 2017

CQRS: Building a pipeline using MediatR behaviors

I recently started a new project where we are using MediatR to simplify our CQRS infrastructure. This gives us our basic building blocks to create our queries, commands and the related handlers.

One of the things I wanted to add were some decorators to provide some extra functionality(like authorization, logging, transaction management,…) before and after a request. Turns out I’m lucky as with the release of MediatR 3.0 I can fall back to a built-in functionality called behaviors.

Similar to action filters in ASP.NET MVC, it gives me the opportunity to execute some arbitrary logic before and after a request(command/query). Usage is simple:

  • You have to implement the IPipelineBehavior<TRequest, TResponse> interface:
  • Don’t forget to register the pipeline behavior through your IoC container(StructureMap in the example below)!
Note: As I’m registering this as an Open Generic this behavior will apply to all my messages.

No comments: