eShopOnWeb Architecture (4/16) – uses the MediatR library to keep controllers thin

eShopOnWeb uses Jimmy Bogards MediatR package to keep controllers thin. This package is a simple implementation of the mediator design pattern which is frequently employed to break up controllers into smaller pieces by using handlers to do the work of action methods. 

Below we can see that the MyOrders() action method simply delegates to the GetMyOrdersHandler whose Handle method contains the actual logic for getting orders…

Due to the fact OrderController only requires IMediator and MyOrders doesn’t contain logic the controller is kept thin. Quite often we can see DI constructor explosion or action method explosion in controllers such as…

… so in this instance MediatR helps but IMHO there are easier ways to solve these problems without having to use MediatR which can make debugging quite hard.

One thing to do is simply have only one action per controller (combined with attribute routing) and delegate the logic itself to domain services as we would normally do.

If we see a proliferation of methods in our service classes we can switch to a one (or few) use case per service approach. This would probably then be a 1-1 with our controller action methods which is similar to MediatR in the sense that each handler processes a single request. IMHO the controller action method -> service method flow is much easier to understand and debug than the equivalent MediatR approach.

The one thing that many devs including it’s author Jimmy Bogard do like about MediatR is that it provides a uniform interface for all actions. Developers don’t need to consider when to take break up service classes or what scope they should have as every request get its own handler all the time. In Jimmy’s own words from Reddit..

What do you think? Do you like to use MediatR in your apps?

Leave a Reply

Your email address will not be published. Required fields are marked *