68

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

developer9969
  • 2,965
  • 3
  • 26
  • 58
  • 2
    Playing devil’s advocate here is a post on why you need to think twice before bringing it into the project - https://alex-klaus.com/mediator/ – Alex Klaus Jan 01 '20 at 09:57

2 Answers2

81

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.

Overview of the Mediator Pattern

A mediator is an object that makes decisions on how and when objects interact with each other. It encapsulates the “how” and coordinates execution based on state, the way it’s invoked or the payload you provide to it.

In regards to the spirit of your question, you should really have a look at this site:

Simplifying Development and Separating Concerns with MediatR

MediatR is an open source implementation of the mediator pattern that doesn’t try to do too much and performs no magic. It allows you to compose messages, create and listen for events using synchronous or asynchronous patterns. It helps to reduce coupling and isolate the concerns of requesting the work to be done and creating the handler that dispatches the work.

More about Mediator Pattern

Can you in your own opinion describe why would you use it

The mediator pattern helps decoupling your application via communication through a mediator (its a thing) .

Usually a program is made up of a large number of classes. However, as more classes are added to a program, the problem of communication between these classes may become more complex. This makes the program harder to read and maintain. Furthermore, it can become difficult to change the program, since any change may affect code in several other classes.

With the mediator pattern, communication between objects is encapsulated within a mediator object. Objects no longer communicate directly with each other (decoupling), but instead communicate through the mediator. This reduces the dependencies between communicating objects, thereby reducing coupling.

In modern software, the mediator pattern is usually found within many frameworks, however you can create your own, or use one of many that are available.

From here, i think you should probably just do more research, i mean usually you figure out you need these things before you research them, however in this case i think you really need to find some good examples to know whether you want the Mediator Pattern, and even more The MediatR library

Update

wired_in had some great practical comment on this

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.

and

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

Noctis
  • 10,865
  • 3
  • 38
  • 74
TheGeneral
  • 69,477
  • 8
  • 65
  • 107
  • thanks for your reply.I am trying to learn MediatR why the downvote I dont get it – developer9969 Jun 03 '18 at 05:24
  • 3
    @developer9969 because this a fairly opinionated question, its very broad, any potential winning answer is just your favorite – TheGeneral Jun 03 '18 at 05:27
  • 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. – developer9969 Jun 03 '18 at 05:28
  • @developer9969 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, – TheGeneral Jun 03 '18 at 05:30
  • .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 it – developer9969 Jun 03 '18 at 05:32
  • @developer9969 updated – TheGeneral Jun 03 '18 at 05:39
  • THANKS. I wil take it from here and look for some samples!!!brilliant answer – developer9969 Jun 03 '18 at 05:43
  • @developer9969 Please take that to meta. But read this first: https://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. – Yunnosch Jun 03 '18 at 07:22
  • @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 replying – developer9969 Jun 03 '18 at 07:31
  • 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. – Konrad Aug 01 '18 at 14:29
  • 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... – Konrad Aug 01 '18 at 14:31
  • 28
    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. – wired_in Sep 13 '18 at 17:36
  • 11
    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. – wired_in Sep 13 '18 at 17:46
  • @Saruman I don't mind – wired_in Sep 14 '18 at 20:15
  • 3
    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. – Derek Greer Apr 18 '19 at 23:37
  • 1
    @developer9969 , @wired_in , @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. – Mohsen Sep 03 '19 at 11:19
  • 1
    If the two comments at the end (after Update) were an answer I'd upvote it. – Scott Hannen Jun 03 '20 at 16:27
10

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.

Holtz Ilya
  • 336
  • 4
  • 8