How to be more declarative when implementing CQRS with MediatR in .Net Core.

Akojavakhishvili
2 min readDec 2, 2019

--

MediatR is just a “simple mediator implementation in .NET” and is mainly used for implementing CQRS (command query responsibility segregation) in .Net Core. It has several useful features, such as IPipelineBehavior middleware, which we will discuss in this article.

Let’s begin with the basics of MediatR. We will use Autofac modules for dependency injection.

Simple MediatR command:

Simple MediatR command handler:

MediatR usage in controller:

As you can see, nothing complicated here yet.

Now, let’s introduce some IPipelineBehavior use cases, which I came across during the development of a back-end for a social network app.

We’ll be using the Marker Interface pattern to filter out the commands not affected by custom IPipelineBehaviors.

Let’s suppose we have a simple CreatePost Command in our .net core app.

First, we’ll use IPipelineBehavior to make command handling transactional (Performing all the database updates caused by a particular command in a single transaction). Such commands will implement ITransactionalRequest (Marker Interface).

Implement ITransactionalRequest.

Create new TransactionalBehavior.

And register it in an Autofac module.

Secondly, we’ll make command handling idempotent. To achieve this, our command should simply implement IIdempotentRequest.

Implement IIdempotentRequest.

Create new IdempotentBehavior.

And register it in an Autofac module.

DDD (Domain Driven Design) integration

We can also use IPipelineBehaviour to easily integrate DDD domain event publishing in our app. Let’s suppose we generate a domain event while handling a particular command. To make this easy, such command can implement IDomainEventPublisherRequest.

Implement IDomainEventPublisherRequest.

Create new DomainEventPublisherBehavior.

But wait, there’s more! These generated domain events will be published eventually without us having any control over it. However, we can easily make the publishing of all these events transactional. To achieve this, first we make our initial command transactional (implement ITransactionalRequest) and we register the transactional behavior before the publisher behavior. Doing this tells MediatoR to make publishing transactional as well.

You can find the project in this Github repository.

I hope you found this article helpful.

--

--