Micro services or API layer design the most non avoidable design patterns, any product can adopt to evolve into more robust design. It is interesting to look at different patterns from rest or aggregated api with graphql as BFF or server less and working with cloud and Messaging ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Interesting thing about this article is bring ing mediaR pattern into clean architecutre which can support CQRS or command and Query much effectively at the same time manage required layers supported by Cleanr architecutre.
Easy and useful Pattern to make code clean and structure.
Clean Code Architecture or often called Onion Architecture is a layered architecture that makes your project easy to manage and test. You can find the common pictures of this concept from visual diagram below. If you don't know about clean code architecture, there are some useful links you can visit.
CQRS stands for “Command Query Responsibility Segregation”. The main purpose of this pattern is to split responsibility of commands (saves) and queries (reads) into different models.
If we think about commonly used CRUD pattern, we think it as working on same data model to perform CRUD operations. For an example if we have a user model class, we usually performs the CRUD operations on that user model class. However CQRS would instead have us split these operations into two models, one for the queries (Read), and another for the commands (Create-Update-Delete).
Mediator pattern
Mediator pattern is used to reduce communication complexity between multiple objects or classes. This pattern provides a mediator class which normally handles all the communications between different classes and supports easy maintenance of the code by loose coupling.
We can see in the image above, Controller Service sends a message to the Mediator, the Mediator then invokes one or multiple services to handle the message. There is no direct dependency between green and blue components.
MediatR library for CQRS and Mediator pattern
MediatR is a .Net library that is used to implement CQRS with mediator pattern. However this library has a limitation. It only works on 'in process' CQRS implementation. The term 'in process' means .NET library that manages interactions within classes on the same process. It is not an appropriate library to use if we wanted to separate the commands and queries across two systems. In that case, a better approach would be to a message broker such as Kafka or RabbitMq.
Setting up project
Project Setup
First off, let’s open Visual Studio and create a new ASP.NET Core Web Application, selecting API as the project type.