public class CreateOrderCommandHandler
: IRequestHandlerbool
>
{
That is the code that correlates commands with command handlers. The handler is just a simple class,
but it inherits from
RequestHandler , where T is the command type, and MediatR makes sure it is
invoked with the correct payload (the command).
Apply 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 behaviors, too.
public class MediatorModule : Autofac.
Module
{
protected override void
Load
(ContainerBuilder builder)
{
builder.
RegisterAssemblyTypes
(
typeof (IMediator).
GetTypeInfo
().
Assembly
)
.
AsImplementedInterfaces
();
// Register all the Command classes (they implement IRequestHandler)
// in assembly holding the Commands
builder.
RegisterAssemblyTypes
(
typeof (CreateOrderCommand).
GetTypeInfo
().
Assembly
).
AsClosedTypesOf
(
typeof (IRequestHandler<,>));
// Other types registration
//...
builder.
RegisterGeneric
(
typeof (LoggingBehavior<,>)).
As
(
typeof (IPipelineBehavior<,>));
builder.
RegisterGeneric
(
typeof (ValidatorBehavior<,>)).
As
(
typeof (IPipelineBehavior<,>));
}
}
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.