Mediator Pattern in ASP.NET Core Applications
By: João Simões
Tags: Event Sourcing, Csharp, Cqrs, Aspnetcore, Mediator Pattern

The project

The source code for this article can be found on GitHub.

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 entities for products and events, to store both the business data and mutations history:

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

services.AddDbContext<ApiDbContext>(o =>

{

o.UseInMemoryDatabase("ApiDbContext");

});

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 ICommandHandler , IQueryHandler and IEventHandler :

services.AddMediator(o =>

{

o.AddHandlersFromAssemblyOf<Startup>();

});

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

private readonly IMediator _mediator; public ProductsController(IMediator mediator)

{

_mediator = mediator;

}

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. As stated before, I made some articles more specific for those use cases.

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 that will serialize and store it into the events table.

Open the CreateProductCommandHandler file, inject the IMediator instance and broadcast the event before saving flushing all changes into the database:

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.