CQRS Pattern With MediatR in .Net Core
CQRS(Command Query Responsibility Segregation) Pattern, where you create two different stream for data processing i.e. one for all DML i.e. data post/write actions through command and another one is DQL i.e. read/select actions which is with query.
Use cases when/where to use?
- Where your database related changes happening frequently then, its better to separate, so that one change could not impact other.
- When your database having lots of load and you might be interested to distribute read and write to different database, so in that case you might need to host your read and write app separately and point to different database.
- When you have some crucial write operations and you do not want to handover to all the devs to work on in it but all devs can work on read operations.
For this demo, I used "MediatR" pckage, so what is "MediatR"?
The mediator design pattern controls how a set of objects communicate and helps to reduce the number of dependencies among these objects that you must manage. In the mediator design pattern, objects don’t communicate with one another directly, but through a mediator.
It supports request/response, commands, queries, notifications and events, synchronous and async with intelligent dispatching via C# generic variance.
With below example if you see for two get and add class i.e. "GetTodoById.cs" and "AddTodo.cs" I do not require to inject DI into startup.cs while I am using into TodoController, instead it is getting managed by MediatR DI I added into startup.cs and my both class implementing MediatR.
I have repository class which will return some fixed list of items with Todos porperty:
Add "MediatR" packages to solution:
Created separate folder/file for GetTodoById() (ideally, it will go into defferent solution to have all select/read related stuff as part of CQRS pattern, but just for demo, I just created separate file):
Created separate folder/file for AddTodo() (ideally, it will go into different solution to have all select/read related stuff as part of CQRS pattern, but just for demo, I just created separate file):
Created controller to use both get and add Todo:
Added DI to startup.cs for MediatR and repository class:
My swagger result for GetTodoById():
Categories/Tags: cqrs~mediatr