280
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns
Figure 7-25. Using the Mediator pattern in process in a single CQRS microservice
The above diagram shows a zoom-in from image 7-24: the ASP.NET Core controller sends the
command to MediatR’s command pipeline, so they get to the appropriate handler.
The reason that using the Mediator pattern makes sense is that
in enterprise applications, the
processing requests can get complicated. You want to be able to add an open number of cross-
cutting concerns like logging, validations, audit, and security.
In these cases, you can rely on a
mediator pipeline (see
Mediator pattern
) to provide a means for these extra behaviors or cross-
cutting concerns.
A mediator is an object that encapsulates the “how” of this process: it coordinates execution based on
state, the way a
command handler is invoked, or the payload you provide to the handler. With a
mediator component, you can apply cross-cutting concerns in a centralized and transparent way by
applying decorators (or
pipeline behaviors
since
MediatR 3
). For more information, see the
Decorator
pattern
.
Decorators and behaviors
are similar to
Aspect Oriented Programming (AOP)
, only applied to a
specific process pipeline managed by the mediator component. Aspects in AOP that implement cross-
cutting concerns are applied based on
aspect weavers
injected at compilation time or based on object
call interception. Both
typical AOP approac
hes are sometimes said to work “like magic,” because it is
not easy to see how AOP does its work. When dealing with serious issues or bugs, AOP can be difficult
to debug.
On the other hand, these decorators/behaviors are explicit and applied only in the context
of the mediator, so debugging is much more predictable and easy.
For example, in the eShopOnContainers ordering microservice, has an implementation of two sample
behaviors, a
LogBehavior
class and a
ValidatorBehavior
class. The implementation of the behaviors is
explained in the next section by showing how eShopOnContainers uses
MediatR
behaviors
.
281
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns
Dostları ilə paylaş: