Skip to content

Mediator Pattern using MediatR and Unity

MediatRIn a couple previous posts I’ve discussed using Query Objects instead of Repositories and the Mediator pattern.  I find creating query objects being used with the command pattern much cleaner than polluting repositories with a ton of query methods.

The concept is nothing new as many people already use the command pattern in the context of executing commands/behavior following CQRS.   However, there is nothing wrong with using the same patterns for the query side.

I’ve been using my own home grown solution of the mediator pattern in a few different projects but had nothing really formalized.  I was thinking about creating a simple library until I stumbled upon MediatR created by Jimmy Bogard.

It is incredibly simple and only has one dependency, CommonServiceLocator.

The Github repo has a good set of docs and some examples with different dependency injection containers.

Unity RegisterType

I did notice the Unity example didn’t quiet work as described in the example.

The Mediator class takes a ServiceLocatorProvider in its constructor which was not being resolved properly by Unity.

In order to get it functioning correctly, I defined an injection factory and created the Mediator and passed in the UnityServiceLocator.

My complete Unity configuration which is also using MediatR to publish events from NEventStore:

MediatR v2.0

Although v1 has a dependency on CommonServiceLocator, it appears that v2.0 will not have any external dependencies.

MediatR

 

 

7 thoughts on “Mediator Pattern using MediatR and Unity”

  1. Pingback: Thin Controllers with CQRS and MediatR

  2. Pingback: Identify Commands & Events - CodeOpinion

  3. Pingback: Validating Commands

  4. Pingback: Mediator Pattern with Hangfire - CodeOpinion

Leave a Reply

Your email address will not be published. Required fields are marked *