Applying cross-cutting concerns when processing commands with the Behaviors in MediatR

There is one more thing: being able to apply cross-cutting concerns to the mediator pipeline. You can also see at the end of the Autofac registration module code how it registers a behavior type, specifically, a custom LoggingBehavior class and a ValidatorBehavior class. But you could add other custom behaviours, too.

Image

That LoggingBehavior class can be implemented as the following code, which logs information about the command handler being executed and whether it was successful or not.

Image

Just by implementing this behavior class and by registering it in the pipeline (in the MediatorModule above), all the commands processed through MediatR will be logging information about the execution.

The eShopOnContainers ordering microservice also applies a second behavior for basic validations, the ValidatorBehavior class that relies on the FluentValidation library, as shown in the following code:

Image

The behavior here is raising an exception if validation fails, but you could also return a result object, containing the command result if it succedded or the validation messages in case it didn’t. This would probably make it easier to display validation results to the user.

Then, based on the FluentValidation library, we created validation for the data passed with CreateOrderCommand, as in the following code: