By promoting loose coupling this pattern implements a mediator object where other objects communicate with it rather than each other
when to use cqrs meditor –
services calling each other – there is a box need to hit request and respone
cleanliness of large code bases
separate writes and reads -like ui team only wants to work on reads , so no impact on other teams using writes
code portability – box you can use
for simple crud – no need to use cqrs as proper abstractions resolve it, and its less complexity
Simply saying we need to remember 3 things
Mediator – middle dispatch stuff
Command Query – message which mediator know which handler to trigger
Handler
mediator tells which handler to pick based on query or command submitted
queries are for getting information about vehicles (in our app, we used vehicles)
commands are to do something with vehicles
Also, we need to use a pipe which is like a middleware for mediator (not a middleware for asp.net core) where we can do some stuff for request and response
Here in our app we have IPipelineBehavior – mediator interface which says do something with the message coming in and going out
There is other stuff we can add like caching in pipes, grab stuff from DB, entity framework transactions, mark queries as iqyeruable
Also we have request and responses. so we create a wrapper on top of them
there is also a mediator publish which we can use where it send notifications to bunch of handlers . which is like fire and forget
we can use this where we are using mediator.send() . so we can use mediator.publish
In our app, we have api project and services project.
in api , we need to configure our services in startup
services.AddHttpContextAccessor();
//register the pipe. we can add multiple pipes and executed by the order they added from top to bottom
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(AuthorizedIdPipe<,>));
//register medieators. Get where assemblies of handlers live
services.AddMediatR(typeof(GetAllVehiclesQuery).Assembly);
we used Infrastructure as a pipe for getting AuthorisedId
Add Services proj in Web Api . The controller will be using the commands and queries for the controller actions like:
[HttpPost]
public Task> Index([FromQuery] CreateVehicleCommand command)
{
return mediator.Send(command);
}
In Services, we have vehicle model and commands and queries and a wrapper for Requests
Code in Github: https://github.com/pbndru/Phani.CQRS