Command And Mediator Patterns In ASP.NET Core Using MediatR

In this article, I will explain command patterns and how we can implement them with a third party library which is built on command patterns, and how we can use it in ASP.NET Core to solve our problems and make the code clean. So, we will be going through the following basics.

  • What is a Command Pattern?
  • A simple example of Command Patterns and a short description of Mediator Patterns.
  • What are thin controllers in MVC, how our implementation makes the controller thin?
  • What is MediatR?
  • How we can use MediatR in our .NET Core application
  • Examples using commands and events

Basically, a command pattern is a data-driven design pattern that falls in the category of behavior pattern. A command is some operation or action that we can perform and it can be the part of an activity. An activity can have one or many commands and implementations.

We can say that the request wrapped under an object as a command is passed to an invoker object. The Invoker (Broker) object looks for the appropriate object which can handle this command, and passes the command to the corresponding object which executes the command.

A simple example of this is messages of multiple types. The Message class contains properties and methods like SendEmail() and SendSms(). Two type of commands are used and an interface is required which should be inherited by EmailMessageCommand and SMSMessageCommand classes. A broker class is also used which invokes the particular type of message class to handle the operation.

Command, Mediator Pattern In ASP.NET Core Using Mediatr
Main class
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             Message message = new Message();  
  6.             message.CustomMessage = "Welcome by Email";  
  7.             EmailMessageCommand emailMessageCommand = new EmailMessageCommand(message);  
  9.             Message message2 = new Message();  
  10.             message2.CustomMessage = "Welcome by SMS";  
  11.             SmsMessageCommand smsMessageCommand = new SmsMessageCommand(message2);  
  13.             Broker broker = new Broker();  
  14.             broker.SendMessage(emailMessageCommand);  
  15.             broker.SendMessage(smsMessageCommand);  
  16.             Console.ReadKey();  
  18.         }  
  19.     }  
  1. public class Message  
  2.     {  
  3.         public string CustomMessage { get; set; }  
  5.         public void EmailMessage()  
  6.         {  
  7.             Console.WriteLine($"{CustomMessage} : Email Message sent");  
  8.         }  
  10.         public void SmsMessage()  
  11.         {  
  12.             Console.WriteLine($"{CustomMessage} : Sms Message sent");  
  13.         }  
  14.     }  
Interface and Broker
  1. public interface IMessageCommand  
  2. {  
  3.     void DoAction();         
  4. }  
  6. public class Broker  
  7. {  
  8.     public void SendMessage(IMessageCommand command)  
  9.     {  
  10.         command.DoAction();  
  11.     }  
  12. }  
  1. public class EmailMessageCommand : IMessageCommand  
  2.     {  
  3.         private Message oMessage;  
  5.         public EmailMessageCommand(Message oMessage)  
  6.         {  
  7.             this.oMessage = oMessage;  
  8.         }  
  10.         public void DoAction()  
  11.         {  
  12.             oMessage.EmailMessage();  
  13.         }  
  14.     }  
  16.     public class SmsMessageCommand : IMessageCommand  
  17.     {  
  18.         private Message oMessage;  
  20.         public SmsMessageCommand(Message oMessage)  
  21.         {  
  22.             this.oMessage = oMessage;  
  23.         }  
  24.         public void DoAction()  
  25.         {  
  27.             oMessage.SmsMessage();  
  28.         }  
  29.     }  
Command, Mediator Pattern In ASP.NET Core Using Mediatr 
What are thin controllers and why we need them? What is MediatR?

When we start development in MVC framework, the logic is written in action methods of the controller; like we have a simple application of eCommerce where users are supposed to put orders. We have a controller, OrderController, which is used to manage the orders. When a user places the order, we are supposed to save records in the database.

Up until this, we have a simplified code. After some time, however, we realize that there is also a business requirement of the confirmation email. Now, the second step is to send the confirmation email to the customer. Later on, we realize that after this step, we need to perform another operation as well, i.e., logging the information and so on. In the end, we realize that we need to save this user's information to the CRM too. The point is that it will grow the size of the controller. Now, we can call it a fatty controller.

A Command-based architecture allows us to send commands to perform some operation and we a have separate handler of command that makes the separation of concern and improves the single responsibility as well. To implement this architecture, we can use a third-party library, like MediatR (Mediator Pattern) which does a lot of groundwork for us. The mediator pattern defines an object that encapsulates how a set of objects interact.

Advantages of Mediator Pattern and how MediatR can help us
  • The mediator pattern defines an object that encapsulates how a set of objects interact (as defined by Wikipedia).
  • It promotes loose coupling by keeping the objects from referring to each other explicitly.
  • It promotes the Single Responsibility Principle by allowing the communication to be offloaded to a class that handles just that.

How MediatR library helps us

MediatR allows us to decouple our controllers from our business logic by having our controller actions send a request message to a handler. The MediatR library supports two type of operations.

  • Commands (Expect some output as result)
  • Events (Caller do not care what happened next, do not expect result)

We have already discussed the command pattern so it is time to define some commands and issue the command by using MediatR.

Installation in ASP.NET Core

We will need to install MediatR and MediatR.Extensions.Microsoft.DependencyInjection packages from NuGet.

Command, Mediator Pattern In ASP.NET Core Using Mediatr 
Command, Mediator Pattern In ASP.NET Core Using Mediatr

When these two packages get installed, then we need to add services.AddMediatR(); to the startup.cs file. It looks like this.

Command, Mediator Pattern In ASP.NET Core Using Mediatr 

Now, we can use the MediatR library in our .NET Core project.


The first example demonstrates the use of the Request/Response type of operation by using MediatR. It expects some response against the request.

The second example will show you an event where multiple handlers do their job and callers do not care about what is happening next and do not expect any result/response.

First Example

In this scenario, we want to register the user and expect some response against the request. If the response returns true, we can do further operations like a logged in user.

First, we need to create a class which is inherited from IRequest<T>.

  1. public class NewUser: IRequest<bool>  
  2.   {  
  3.       public string Username { get; set; }  
  4.       public string Password { get; set; }          
  5.   }  

IRequest<bool> means that the response of request is boolean.

Now, a handler is required to handle this type of request.

  1. public class NewUserHandler : IRequestHandler<NewUser, bool>  
  2.   {         
  3.       public Task<bool> Handle(NewUser request, CancellationToken cancellationToken)  
  4.       {  
  5.           // save to database  
  6.           return Task.FromResult(true);  
  7.       }  
  8.   }  

Now that we have the command and its handler, we can call MediatR to do some operation in our Controller.

These are the Home Controller action methods. 

  1. public class HomeController : Controller  
  2.     {  
  3.         private readonly IMediator _mediator;  
  5.         public HomeController(IMediator mediator)  
  6.         {  
  7.             _mediator = mediator;  
  8.         }  
  9.        [HttpGet]  
  10.         public ActionResult Register()  
  11.         {  
  12.             return View();  
  13.         }  
  15.         [HttpPost]  
  16.         public ActionResult Register(NewUser user)  
  17.         {  
  18.             bool result = _mediator.Send(user).Result;  
  20.             if (result)  
  21.                 return RedirectToAction("Login");  
  23.             return View();  
  24.         }  
  25.       }  
The conclusion of the first example -

The Register action method is decorated with [HttpPost] attribute and accepts the new user registration requests. Then, it asks MediatR to do action. It expects the result/response from the request and if the result is true, it redirects the user to the login page.

Here, we have clean code and most of the work is done outside of the Controller. This achieves the separation of concerns (SoC) and single responsibility in terms of the handler for different operations.

In our second example, we will demonstrate the scenario where multiple handlers are used to perform different operations against a command.

Second Example

In this case, we inherited the NewUser class from INotification.

  1. public class NewUser : INotification  
  2. {  
  3.     public string Username { get; set; }  
  4.     public string Password { get; set; }  
  5. }  

Now, there are three handlers which are executed one by one to perform their job. These are inherited from INotificationHandler.

  1. public class NewUserHandler : INotificationHandler<NewUser>  
  2.     {  
  3.         public Task Handle(NewUser notification, CancellationToken cancellationToken)  
  4.         {  
  5.             //Save to log  
  6.             Debug.WriteLine(" ****  Save user in database  *****");  
  7.             return Task.FromResult(true);  
  8.         }  
  9.     }  

The second handler is defined in the below code.

  1. public class EmailHandler : INotificationHandler<NewUser>  
  2.     {  
  3.         public Task Handle(NewUser notification, CancellationToken cancellationToken)  
  4.         {  
  5.             //Send email  
  6.             Debug.WriteLine(" ****  Email sent to user  *****");  
  7.             return Task.FromResult(true);  
  8.         }  
  9.     }  

Here is the code for the third handler.

  1. public class LogHandler : INotificationHandler<NewUser>  
  2.     {  
  3.         public Task Handle(NewUser notification, CancellationToken cancellationToken)  
  4.         {  
  5.             //Save to log  
  6.             Debug.WriteLine(" ****  User save to log  *****");  
  7.             return Task.FromResult(true);  
  8.         }  
  9.     }  

And, our controller code looks like this.

  1. public class AccountsController : Controller  
  2.     {  
  3.         private readonly IMediator _mediator;  
  4.         public AccountsController(IMediator mediator)  
  5.         {  
  6.             _mediator = mediator;  
  7.         }  
  8.         [HttpGet]  
  9.         public ActionResult Login()  
  10.         {  
  11.             return View();  
  12.         }  
  13.         [HttpGet]  
  14.         public ActionResult Register()  
  15.         {  
  16.             return View();  
  17.         }  
  19.         [HttpPost]  
  20.         public ActionResult Register(NewUser user)  
  21.         {  
  22.             _mediator.Publish(user);  
  23.             return RedirectToAction("Login");  
  24.         }  
  25.     }  
The conclusion of the second example -

The output of this application is as following.

When a user gets registered, then three of the handlers get executed one by one -  NewUserHandler, EmailHandler, and LogHandler respectively and perform their operation.

Here, we used a Publish method instead of the Send function. Publish will invoke all handlers that subscribe to the type of NewUser class. This is just an example, we can think in term of commands and then we can do some action accordingly as I discussed in the command pattern.

How can Mediatr be helpful?

It can be used to hide the detail of implementation, used to make the controller code more clean and maintainable, multiple handlers can be reused, and each handler has its own responsibility so it is easy to manage and maintain.

In my next article, I will try to explain a CQRS architecture pattern and its advantages and how we can use MediatR to implement the CQRS.