The theory behind the mediator pattern

The mediator pattern is a way to encapsulate logic behind a unique entry point. It uses the concept of requests, responses, commands, or events to abstract the implementations behind a single entry point. This way of implementing the application logic helps the developers in your team keep the logic separated from the web part of the application. To understand how the mediator pattern works, let's take a look at its components.

The preceding schema describes a simple implementation of the mediator pattern. The consumer of the mediator calls the Send method by referring to the IMediator interface. The mediator implementation passes a specific type of the IRequest interface. Therefore, the Mediator instance dispatches the messages to the destination handler, which is represented by the IMessageHandler implementation, using the concrete implementation of the IRequest interface. In the next chapter, we will learn how to use an IMediator interface to dispatch messages to specific handlers.

Furthermore, we will use the mediator pattern with the command approach. There are slightly different ways to implement the mediator pattern. The project that we'll be covering in this chapter uses a very popular mediator NuGet packaged called MediatR. MediatR is an all-in-one implementation of the mediator pattern that covers in-process messaging. You can find more information about the MediatR project on GitHub: https://github.com/jbogard/MediatR.

For the purpose of the cart service implementation, we're going to use the following components, all of which have been exposed by the MediatR library:

  • The IMediator interface is the main entry point of the mediator pattern. It exposes a Send method, which is used to dispatch a command or a request to a specific handler in order to obtain a result.
  • The IRequestHandler interface is a generic interface that's used to define the implementation of a handler. Each IRequestHandler type requires an IRequest type, which represents the request that's sent through the IMediator interface.
  • The IRequest interface defines the request or the command type that's used to execute a specific handler.

Now that we have more information about how the mediator pattern works, we can continue with the concrete implementation of the cart service solution. In the next section, we will look at how we can define the domain model of the service and implement the data access layer abstraction over the Redis data store. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.211.134