With MediatR, we packed the power of a CQS-inspired pipeline with the Mediator pattern into a Clean Architecture application. We broke the coupling between the request delegates and the use case handler (previously a service). A simple DTO, such as a command object, makes endpoints and controllers unaware of the handlers, leaving MediatR as the middleman between the commands and their handlers. Due to that, the handlers could change along the way without impacting the endpoint.Moreover, we could configure more interaction between the command and the handler with IRequestPreProcessor, IRequestPostProcessor, and IRequestExceptionHandler. These allow us to extend the MediatR request pipeline with cross-cutting concerns like validation and error handling.MediatR helps us follow the SOLID principles the same way as the Mediator and CQS patterns combined. The only drawback of the overall design, which has nothing to do with MediatR, is that we used the commands as the DTOs. We could create custom DTOs and map them to command objects. However, you will understand in the next chapter where I was heading with this transitory design.
Summary
In this chapter, we looked at the Mediator pattern, which allows us to cut the ties between collaborators, mediating the communication between them. Then we studied the CQS pattern, which advises the division of software behaviors into commands and queries. Those two patterns are tools that cut tight coupling between components.Afterward, we updated a Clean Architecture project to use MediatR, an open-source generic mediator that is CQS-oriented. There are many more possible uses than we explored, but this is still a great start. This concludes another chapter exploring techniques to break tight coupling and divide systems into smaller parts.All those building blocks lead us to the next chapter, where we piece those patterns and tools together to explore the Vertical Slice Architecture.
Leave a Reply