Introduction To MediatR Pattern

Introduction

 
MediatR Pattern/Library is used to reduce dependencies between objects. It allows in-process messaging,but it will not allow direct communication between objects. Instead of this it forces to communicate via MediatR only, such as classes that don't have dependencies on each other, that's why they are less coupled.
 

Advantages of using MediatR

  • Remove Dependencies, that's why it's less coupled.
  • Using MediatR either do send or receive a message.
  • It is Unambitious.
  • It allows in message processing.
  • It promotes loose coupling so the object does not depend on each other.
  • It is one-way broadcast communication.
  • You can reuse classes using MediatR.

Installing MediatR Library

 
You can install the MediatR library using NuGet or Package Manger Console. Using the package manager console, you need to fire the below command:
 
Introduction To MediatR Pattern
 
Now we installed MediatR Library using the above command in our project. Then you can install MediatR.Extensins.Microsoft.DependencyInjection in the project using the below command.
 
Introduction To MediatR Pattern
 
Once the above two package installation has completed, then you can register mediatr in startup class using services.AddMediatR(Assembly.GetExecutingAssembly());
 
Using MediatR pattern every call contains a request and handler. This request sent to the handler which processes the request. When you send a request, only one and one handler will be called and it will return a response for that appropriate request. It doesn't really make sense to have more than one handler for a given request. Basically, it supports as I said in the above two messages, like Request/Response and Notification.
 
Let's understand it by using diagram so it will give an easy way to understand the MediatR Concept
Introduction To MediatR Pattern
As we discussed above MediatR is promotes Loose coupling so objects do not depend on each other. MediatR provides One Way broadcast communication. The main goal is only for MediatR to disallow direct communication between objects and instead force them to communicate through MediatR. In the above example, we have one service and we create MediatR then by using this MediatR we can use handler it in services. MediatR either does send or receive the message.
 

Conclusion

 
By using the MediatR Pattern, we can reduce dependencies between objects. It allows in Message Processing. It is a good pattern to use for reducing dependence on objects and avoid direct communication. In the next article, we will see the MediatR pattern with an example.
 
I hope this article will help you to understand the concept of MediatR Pattern. Let me know through comment if you have any concerns regarding this.