Home > other >  MediatR conventions in CQRS
MediatR conventions in CQRS

Time:09-19

I am using MediatR and CQRS in a real project using the Clean Architecture principles.

Is it correct to:

  1. Call Command from NotificationHandler?

  2. Call Command in Command?

  3. Call Query in Command?

If you have some resource for these principle, please share them with me.

CodePudding user response:

If you have some resource for these principle please share with me.

A great resource is this video enter image description here

CodePudding user response:

Mediator handlers, commands, queries and notifications should follow the Single responsibility principle (SRP). They should do as little as possible, be atomical. Calling other commands, queries or notifications within a handler is a bad habit as it creates coupling.

CodePudding user response:

MediatR is a simple mediator pattern implementation in .NET as it keeps things separated and contributes to Single Responsibility Principle.

And CQRS stands for Command and Query Responsibility Segregation, which results in a pattern separating both read and write to maximize performance and scalability.

MediatR has 2 types of messages:

  1. Request and response messages that will dispatch a single handler
  2. Notification messages that will dispatch multiple handlers

Requests describe your commands and query behavior as they are fairly simple and specific.

Handler is what you will need to manage/solve a request. Where each request has its own handler.

Commands are where you will perform Insert, Update, and Delete operations.

Queries are where you will perform read operations only.

Notifications is where you will manage/solve a single request by using multiple handlers. So in this case you will create a notification message and create the corresponding handlers for your notification.

Remember that you should know the engineering functionalities of your application and based on it decide whether to use a request/response message or notification message. And more importantly, do not try to mix and match these 2 types of messages as you wish because you will break the mean of these patterns.

So my question is why would you need to call a command from the notification handler? and why do you want to mix 2 commands? and why would you mix the read and writes of your application?

If you understand the 2 types of messaging in MediatR you will know the answer to your question and for any future questions

Some great Resources:

Use MediatR in ASP.NET or ASP.NET Core

Intro to MediatR - Implementing CQRS and Mediator Patterns

Clean ASP.NET Core API using MediatR and CQRS | Setup

This video talks about notifications: The 2 MediatR features people don't know about but should

  • Related