MediatR when and why I should use it? [closed]
Asked Answered
F

2

120

It might have been asked before but I cannot find even in the official site why I should use MediatR and what problems it solves?

  • Is it because I can pass a single object in my constructor rather than a multitude of Interfaces?

  • Is it a replacement or competitor of ServicesBus etc...

  • Basically what are the benefit and what problem does it solve

I want to buy into it but its not clear to me why I should use it.

many thanks

Fretted answered 3/6, 2018 at 5:17 Comment(1)
Playing devil’s advocate here is a post on why you need to think twice before bringing it into the project - alex-klaus.com/mediatorShaw
S
128

Is it because I can pass a single object in my constructor rather than a multitude of Interfaces?

No.

Is it a replacement or competitor of ServicesBus etc...

No.

Basically what are the benefit and what problem does it solve


Among other things, one of the problem MediatR is trying to solve is DI Constructor Explosion in your MVC controllers

public DashboardController(
    ICustomerRepository customerRepository,
    IOrderService orderService,
    ICustomerHistoryRepository historyRepository,
    IOrderRepository orderRepository,
    IProductRespoitory productRespoitory,
    IRelatedProductsRepository relatedProductsRepository,
    ISupportService supportService,
    ILog logger
    )  

This is a highly debated topic and there is no one-size-fits-all solution, take a look at this question

How to avoid Dependency Injection constructor madness?

If you want to hide dependencies behind even more abstractions, then at this point you will want to take a look at all the options, like refactoring, separating concerns a little more, or other techniques.

In all honesty, the example problem and solution given on the MediatR website is a little suspect, however it does have its uses. In short, you need to choose whats right for you and your environment.

Why you might use it

  1. MediatR simplifies communication between components in a .NET application, often aiding in implementing the CQRS (Command Query Responsibility Segregation) pattern. It allows decoupling of in-process messaging, making it easier to manage and maintain complex interactions within an application.

  2. At its core, the Mediator pattern involves an object, the mediator, which encapsulates how a set of objects interact. MediatR acts as this mediator by handling requests and dispatching them to the appropriate handlers.

  3. By using MediatR, you can avoid direct dependencies between components (like UI and business logic). It allows components to remain isolated, only depending on the MediatR interfaces, not on each other.

Why you might not want to use it

  1. For small or simple applications with minimal complexity, introducing MediatR can add unnecessary overhead. The Mediator pattern, and thus MediatR, is more beneficial in applications with a lot of cross-cutting concerns or where clear separation of commands and queries is necessary. In straightforward applications with a direct flow, the additional layer of abstraction may complicate the codebase without providing significant benefits.
  2. Relying on MediatR means introducing an external dependency into your project. In some scenarios, especially in tightly controlled or highly regulated environments, adding external libraries may be discouraged or require extensive vetting.
  3. Debugging can become more complex with MediatR. Tracing the flow of a request through the system is more straightforward with direct method calls. With MediatR, you have to trace through the mediator and its dispatch mechanisms, which can obscure the direct path from request to response.
  4. If not used judiciously, MediatR can lead to an anti-pattern where too much logic is offloaded to handlers, making them bulky and difficult to manage. It requires discipline to ensure that handlers remain focused and maintainable.
Scheider answered 3/6, 2018 at 5:23 Comment(18)
thanks for your reply.I am trying to learn MediatR why the downvote I dont get itFretted
@Fretted because this a fairly opinionated question, its very broad, any potential winning answer is just your favoriteScheider
so what are you supposed to do with an opinionated question .Dont ask. anyway reading the link you provided and however the first problem it solves is "messy constructor" as I pointed out .Not finished reading yet.Fretted
@Fretted Messy constructor isnt its point in life. also as for opinionated questions, there are other places more suited to them, reddit, facebook, code project, softwareenginering stack exchange,Scheider
.Point taken.I guess stackexchange is more appropriate . I guess I need to undestand what the mediator pattern solves first and then what MediatR brings to the plate. Can you in your own opinion describe why would you use itFretted
@Fretted updatedScheider
THANKS. I wil take it from here and look for some samples!!!brilliant answerFretted
@Fretted Please take that to meta. But read this first: stackoverflow.com/help/why-vote It explain why voting in itself is imprtant, which in turn is the reason to allow anonymous downvoting, just to protect downvoters, which do an appreciated job, from reataliation downvotes.Unforgettable
@Yunnosch. ok. it sounds a bit like a "chicken and egg" situation.It's not perfect and it might help but also there are so many "trigger happy" downvoters out there.thanks for replyingFretted
so... without using a mediator I would have one class like OrdersService that depends on other services like ProductsService probably injected in the constructor, with using mediator all I really depend on is a mediator that sends commands.Moselle
Except decoupling, does it give you any other benefit? I think it's just a different way to write your logic. In the end result should be the same. No matter if you use DDD services or commands and handlers...Moselle
All MediatR does is service locate a handler for a request. That is not the mediator pattern. The "mediator" in this instance, does not describe how two objects communicate, it uses inversion of control that is already being used in an application and just provides a useless layer of abstraction that only serves to make an application harder to reason about as a whole. You already achieve decoupling by using standard constructor injection with IoC. I don't understand why people buy into this. Let's create multiple composite roots just so we don't have to put interfaces in our constructor.Kilbride
The OP is completely justified in questioning the point of MediatR. The top responses I hear to the question involve explaining the use of the mediator pattern in general, or that it makes the calling code cleaner. The former explanation assumes that the MediatR library actually implements the mediator pattern, which is far from clear. The latter is not a justifcation for adding another abstraction on top of an already abstracted IoC container, which creates multiple composite roots. Just inject the handler instead of service locating it.Kilbride
@Saruman I don't mindKilbride
I stumbled upon this hoping for a list of pros/cons for using this approach so I didn't have to write up something myself. It's unfortunate this is the accepted answer as it fails to answer the question. Too much is made about the question being opinionated in the comments. The problem is primarily with the accepted answer, not the question. Could the question be worded better? Yes, but ultimately the question asks what problems MediatR seeks to solve. It definitely has an objective purpose. It also has pros and cons. The opinion part best left out is whether the pros outweigh the cons.Marron
@Fretted , @Kilbride , @TheGeneral: It's perfectly useful for having some additional behaviors to all of the handlers without breaking the Open Close Principle. Auditing is an example. If you need to add such a behavior you have to do it upfront, or as a better approach you can leave a door open to add it later without any Shotgun Surgery and changing the working code. Just don't forget to keep the requests and responses immutable. That will let you reason about the code.Illuminance
If the two comments at the end (after Update) were an answer I'd upvote it.Kenelm
As I understand, Mediatr is just a trojan horse to enter service locator anti-pattern to the code, plus some features that most of them are already available in the framework.Amenity
B
18

It is just a way to implement communication between your business logic components.

Imagine that you have:

FirstRequest // which handled by FirstRequestHandler(FirstRequest)
SecondRequest // which handled by SecondRequestHandler(SecondRequest)
ThirdRequest // which handled by ThirdRequestHandler(ThirdRequest)

... there are hundreds of them ...

And then comes ComplexRequest, when ComplexResponse have to be a combination of FirstResponse and ThirdResponse.

How should we solve this?

Well, ComplexRequestHandler would have to inject FirstHandler and ThirdHandler, get their results, and combine them.

But why should ComplexRequestHandler should have access to FirstRequestHandler interface ? Why we should bother to inject First, Third ... OneHundredAndTwentythHandler into our ComplexHandler ?

What MediatR gives us in such use case, is a third party that tells us: "Give me a request, and I"ll get you the right response, Trust me!"

So ComplexHandler doesn't know anything about First and Third Handlers. It knows only about the required requests and responses (which usually are only just wrapping DTOs).

Note: You don't have to necessarily use the MediatR library for that. You can read about the Mediator Pattern and implement one yourself.

Boatman answered 18/2, 2019 at 12:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.