MediatR when and why I should use it? vs 2017 weba

2019-03-14 07:54发布

问题:

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

回答1:

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 solve 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 regaruds to the spirit of your question 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



回答2:

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.