Step 7 Create the event method in the demo service repository class file, then create the event notification under the “Notification” folder. This operation also creates the handler class files, which can handle a single request by multiple handlers—for example, the Email handler class file and the Cache handler class file.

Fig 15 DemoAddNotification object source code.
Fig 16 EmailHandler class source code.
Fig 17 CacheInvalidationHandler class source code.

Note: The Email handler and the cache handler are samples. It can split out the reads/writes into a separate app to Kafka, Service bus and other, etc., then having a second app read from the messages bus.

Step 8 Modify step 5 post method source code. POST method adds triggering the notification mechanism.

Step 9 MediatR can create a logging behavior mechanism. First, create the logging behavior class, which inherits the IPipelineBehavior interface with IRequest interface object and the IResponse interface object.

Second, it adds the constraint variable of the “ILogger” interface with the IResponse object and the IRequest object. The handle function adds the log information function, then returns the “next” function.

Fig 18 LoggingBehavior class source code.

Step 10 Register the logging behavior class in the Startup.cs file.

services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));

Note: The author will recommend the logging behavior class of the MediatR sets the transient behavior in the Startup.cs file.

Reference

Leave a Reply