CQRS Design Pattern With MediatR Library in .NET 8 Microservices

Mehmet Ozkaya
4 min readMar 23, 2024

--

We’re diving into the powerful combination of the CQRS design pattern and the MediatR library in .NET.

https://dotnet.microsoft.com/en-us/learn/dotnet/architecture-guides

This duo is like the dynamic team that makes handling commands and queries in your applications a breeze. Let’s get started!

I have just published course — .NET 8 Microservices: C# 12, DDD, CQRS, Vertical/Clean Architecture.

🌟 MediatR: The Mediator in the Middle

MediatR is this nifty .NET library that acts like a middleman. It’s all about sending your commands (those are like the tasks you want to do) and queries (the information you want to get) to the right places without a fuss. It’s like having a super-organized assistant who knows exactly where everything goes.

✉️ IRequest: The Messenger

In MediatR world, everything that needs to be done, whether it’s a task or fetching data, is wrapped up in what we call messages. These messages use something called the IRequest interface. You can even specify what you expect back after the message is handled by adding a little generic parameter.

🛠️ Handlers: The Doers

For every task or piece of info you need, there’s a handler. These handlers are like your go-to experts for everything. They take in your requests and get things done. Each one is tailored for a specific job, making sure your commands and queries are in the best hands.

🎭 ICommand and IQuery: The Roles

To make things crystal clear, we often split our messages into commands and queries. Commands are all about making changes or doing something, while queries are for digging up information. By defining ICommand and IQuery interfaces, we keep our intentions straight and our code clean.

public interface ICommand<TResult> : IRequest<TResult> { }
public interface IQuery<TResult> : IRequest<TResult> { }

🚀 Bringing It to ASP.NET Core

In an ASP.NET Core application using MediatR, controllers or minimal apis act as the entry point for handling HTTP requests. Instead of implementing the business logic directly within the api actions, these actions delegate the responsibility to MediatR.

When we bring MediatR into an ASP.NET Core application, it’s like adding a layer of magic. Your controllers or minimal APIs just need to pass along the requests, and MediatR takes care of the rest. It knows exactly where to send each command and query, keeping your code neat and focused.

When a controller receives a request, it creates a command or query object and sends it to MediatR. MediatR then dispatches this object to the appropriate handler.

🌐 The Magic of the Mediator Pattern

The mediator pattern is what makes MediatR shine, especially in those complex apps where you’ve got a lot going on. It’s not just about doing the main job; it’s also about taking care of all those extra steps like logging, validation, and security, without cluttering your business logic.

🔄 The Pipeline: Where the Magic Happens

MediatR’s pipeline is where all the action takes place. It’s like a conveyor belt for your requests, where each one gets all the TLC it needs before and after the main task. This is where you can plug in all those important steps, ensuring they’re handled seamlessly every time.

In these applications, handling a request might require additional steps like logging, validation, auditing, and applying security checks. These are known as cross-cutting concerns. MediatR provides a mediator pipeline where these cross-cutting concerns can be inserted transparently. This pipeline coordinates the request handling, ensuring that all necessary steps are executed in the right order.

📚 Real-World Application: EShop Microservices

Let’s take a peek at how this all comes together in a real project, like an EShop microservices setup. Here, we use MediatR to handle everything from logging each request to making sure all the data coming in checks out with validation behaviors. It’s a smooth operation that keeps our microservices running like a well-oiled machine. In EShop Microservices, MediatR is used to implement various behaviors:

  • LogBehavior: A behavior that logs details about the handling of a request.
  • ValidatorBehavior: A behavior that validates incoming requests before they reach the handler.

I have just published course — .NET 8 Microservices: C# 12, DDD, CQRS, Vertical/Clean Architecture.

This is step-by-step development of reference microservices architecture that include microservices on .NET platforms which used ASP.NET Web API, Docker, RabbitMQ, MassTransit, Grpc, Yarp API Gateway, PostgreSQL, Redis, SQLite, SqlServer, Marten, Entity Framework Core, CQRS, MediatR, DDD, Vertical and Clean Architecture implementation with using latest features of .NET 8 and C# 12.

--

--

Mehmet Ozkaya
Mehmet Ozkaya

Written by Mehmet Ozkaya

Software Architect | Udemy Instructor | AWS Community Builder | Cloud-Native and Serverless Event-driven Microservices https://github.com/mehmetozkaya

No responses yet