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, it forces us 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 send or receive a message.
  • It is Unambitious.
  • It allows 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 Manager Console. Using the package manager console, you need to fire the below command:

Package manager

Now we installed MediatR Library using the above command in our project. Then you can install MediatR.Extensions.Microsoft.DependencyInjection in the project using the below command.

Installed media

Once the above two package installations have been completed, then you can register Mediatr in the startup class using services.AddMediatR(Assembly.GetExecutingAssembly());

Using the MediatR pattern every call contains a request and handler. This request is sent to the handler which processes the request. When you send a request, only one handler will be called and it will return a response for that appropriate request. It doesn't make sense to have more than one handler for a given request. It supports as I said in the above two messages, like Request/Response and Notification.

Let's understand it by using a diagram so it will give an easy way to understand the MediatR Concept

Understand mediatR

As we discussed above MediatR 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 handle it in services. MediatR either sends or receives the message.

Conclusion

By using the MediatR Pattern, we can reduce dependencies between objects. It allows Message Processing. It is a good pattern to use for reducing dependence on objects and avoiding 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 comments if you have any concerns regarding this.