For the last few years, Command Query Responsibility Segregation (CQRS) and Event Sourcing (ES) emerged as patterns that can help implement large scale systems, with some risky complexity, by having different models to read or mutate data while also using events as a single source of truth.

The mediator pattern is meant to split responsibilities between a caller and the callee. So instead of having an instance of a class and calling a method directly on it, you ask the mediator to do this for you. While this might sound a lot like doing dependency injection, it actually goes a step further. You don’t even know the interface of the callee. This makes it even more decoupled than you’d have with dependency injection.

The result is that the objects are loosely coupled. They only know about the mediator object, not about each other. Besides the mediator object they’ll likely also have some kind of data transfer object to send parameters for the callee.

For a comparison in the real world, imagine only being able to communicatie with someone or a department through their secretary. You give them a message (the data transfer object) and they pass it on to who you want to reach. Once there’s an answer, the secretary will give it back to you. This way you have no knowledge of who actually answered it.

Advantages and Disadvantages of the Mediator Pattern

The mediator pattern brings a couple of advantages:

  • Less coupling: Since the classes don’t have dependencies on each other, they are less coupled.
  • Easier reuse: Fewer dependencies also helps to reuse classes.
  • Single Responsibility Principle: The services don’t have any logic to call other services, therefore they only do one thing.
  • Open/closed principle: Adding new mediators can be done without changing the existing code.

There is also one big disadvantage of the mediator pattern:

  • The mediator can become such a crucial factor in your application that it is called a “god class”

How to Implement Mediator Pattern ASP.NET Core 3.1

Start by opening Visual Studio and creating an ASP.NET Core 3.1 Web Application with a name and at any location.

Choose an empty project since this is just a demo.

Install the Nuget Swashbuckle.AspNetCore so we can use Swagger to test the API:

Open the file Startup.cs and configure both MVC and Swagger, making it easier to test our web API.

The web API

Since the objective of this article is to show the mediator pattern, a simple endpoint to manage products should be enough:

  • GET /products — search for products using some filters;
  • GET /products/{id} — get a product by its unique identifier;
  • POST /products — create a product;
  • PUT /products/{id} — update a product by its unique identifier;
  • DELETE /products/{id} — delete a product by its unique identifier;

Create a Controllers folder with another Products folder inside, a ProductsController and the following models:

The project should look as follows:

Open the Swagger endpoint (ex: https://localhost:44380/swagger/index.html) and you should see your products endpoint with all the actions:

The database model

For demo purposes we are going to use Entity Framework Core with data stored in-memory.

Install the Nuget Microsoft.EntityFrameworkCore.InMemory:

Create a Database folder, the following database context and a product entity:

Open the Startup.cs file and add the context into the container as an in-memory database:

The project should look as follows:

The mediator

Now that we have created the demo endpoint, models and database, its time to configure the mediator.

Install the Nuget SimpleSoft.Mediator.Microsoft.Extensions which is a specialized package for projects using Microsoft.Extensions.*:

Open the Startup.cs file and add the mediator into the container, scanning the current assembly for all classes implementing ICommandHandlerIQueryHandler and IEventHandler:

Open the ProductsController.cs file and inject into the constructor the IMediator instance:

The handlers

We now have everything we need to start implementing the business logic.

To keep it simple, we are not going to use the mediator pipelines, only focusing on commands, queries, events and their handlers. I’ll demonstrate more complex scenarios in future articles.

Start by creating a folder named Handlers with another inside Products in which we are going to put our POCOs and their handlers.

As a note, remember this is a demo article and this project structure should not be seen as a valid way to organize your solution in your private projects. Commands, queries, events and their handlers should be, at minimum, in different folders.

CreateProductComand

We need data so lets create a command that allows that and will be sent when a request for POST /products is received.

Create a class CreateProductResult that will be returned by the handler with the product unique identifier and a CreateProductCommand, implementing the class Command<CreateProductResult>:

Open the ProductsController.cs file and inside the method CreateAsync send the command into the mediator and map its result:

If we now invoked the endpoint, we would receive an exception saying that no ICommandHandler<CreateProductCommand, CreateProductResult> was found by the container.

We will fix that by creating the class CreateProductCommandHandler with the business logic for this action. For this demo, an InvalidOperationException with a custom message will be thrown when a duplicated code is received:

If you now try to create a product using the Swagger endpoint, you will receive the response with the unique identifier or an internal server error indicating a duplicated code.

The project should look as follows:

GetProductByIdQuery

Time to return a product when a GET /products/:id is received by the web API.

Inside the Handlers/Products folder, create a Product, the GetProductByIdQuery and its corresponding handler, GetProductByIdQueryHandler. Like in the previous handler, for this demo, we are going to throw an InvalidOperationException if the id is unknown:

Open the ProductsController.cs file and inside the method GetByIdAsync fetch the query from the mediator and map its result:.

If you now try to get a product using the Swagger endpoint, you will receive the product or an internal server error indicating an unknown identifier.

CreatedProductEvent

Finally, we are going to create an event that will be broadcast when a product is successfully created.

Just like the previous ones, create a CreateProductEvent and the handler CreateProductEventHandler. This time we are just going to log that a product was created:

Open the CreateProductCommandHandler file, inject the IMediator instance and after saving the changes just broadcast the event:

The project should look as follows:

Conclusion

I hope this article gave you a good idea on how to use the mediator to implement the CQRS and ES patterns even if you are implementing an MVP and can’t spend much time thinking about the architecture but you still want something that can be maintained and extended for some time.

Soon I’ll be explaining more advanced scenarios, like using the mediator pipeline to validate commands before reaching the handler, managing database transactions or even implementing transversal auditing into you application.

Leave a comment

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