preamble
MediatR is a messaging library for .NET , lightweight , simple and efficient , for the implementation of in-process messaging mechanism . It is based on the mediator design pattern and supports various messaging patterns such as request/response, command, query, notification and event. With generic support, MediatR can intelligently dispatch different types of messages and is well suited for domain event processing.
In this article, we will walk through a simple example of how to use the MediatR library to process commands in a .NET 8 project. We will define a command, a handler, and a service for sending commands, demonstrating how to send a command and process it.
preliminary
1、Create project
Create a new .NET 8 WebAPI Standard project, select Enable OpenAPI Support and Use Controller;
dotnet new console -n cd
2. Add MediatR package
Use the following command to add the MediatR package to the project.
dotnet add package MediatR
Example of implementation
1. Register for MediatR
exist file, we need to register the MediatR service.
// Add services to the container. (mr =>{ (typeof(Program).Assembly); });
2、Create notification class
A simple notification class is defined in the projectInfoDemo
It'sINotification
interface implementation.
using MediatR; namespace { public record InfoDemo(string Msg) : INotification; }
It starts by declaring a file namedInfoDemo
record type.
Record types are special classes that are primarily used to represent immutable data types and provide default implementations to simplify object creation and comparison.
public record InfoDemo(string Msg)
: Here is defined a file namedInfoDemo
record type, which accepts a constructor parameter of type stringMsg
. This parameter will become theInfoDemo
A read-only property of the class.: INotification
: Here it is specified that theInfoDemo
class implements theINotification
Interface. In theMediatR
Middle.INotification
interface is used to mark a type to be handled as a Notification, meaning that the type will be used to send a notification without waiting for a response.
Note: This code defines a file namedInfoDemo
notification class, which contains a read-only propertyMsg
, which is used to carry the text of the message. This class can be used to send notifications without expecting any response or result. In practice, you might use theMediatR
(used form a nominal expression)IMediator
interface to send such notifications, and other components to handle them.
3、Create the processor class
Create a notification handler classInfoDemoHandler
, which is used to process the notification and return the response.
it isINotificationHandler<InfoDemo>
interface implementation.
It accepts aILogger<InfoDemoHandler>
Constructor arguments of type_logger
and realizedINotificationHandler<InfoDemo>
Interface.INotificationHandler<T>
The interface isMediatR
The interface provided for processing theT
Type of notification.
using MediatR; namespace { /// <summary> /// Notification Handler Class /// </summary> /// <param name="_logger"></param> public class InfoDemoHandler(ILogger<InfoDemoHandler> _logger) : INotificationHandler<InfoDemo> { /// <summary> /// /// </summary> /// <param name="notification"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task Handle(InfoDemo notification, CancellationToken cancellationToken) { _logger.LogInformation($"InfoDemoHandler Received: {notification}. {}"); return ; } } }
This code implements theINotificationHandler<InfoDemo>
interface with theHandle
method to handle theInfoDemo
Type of notification.
(coll.) fail (a student)MediatR
receiveInfoDemo
When a notification of typeInfoDemoHandler
(used form a nominal expression)Handle
method to handle the notification.
4, create the controller class
Define a file namedMediatorDemoController
Core controller, using theMediatR
Posting terkait untuk.
using MediatR; using ; namespace { [ApiController] [Route("[controller]")] public class MediatorDemoController : ControllerBase { private readonly IMediator mediator; private readonly ILogger<MediatorDemoController> _logger; /// <summary> ///initialization /// </summary> /// <param name="mediator"></param> /// <param name="logger"></param> public MediatorDemoController(IMediator mediator, ILogger<MediatorDemoController> logger) { this.mediator = mediator; _logger = logger; } /// <summary> /// MediatorDemo method /// </summary> /// <returns></returns> [HttpGet(Name = "MediatorDemoMethod")] public string MediatorDemoMethod() { var information = new InfoDemo("Mediator Controller Messages"); (information); _logger.LogInformation($"{} : MediatorDemoController Send: {information}."); return $"Ok"; } } }
Description:This code defines a file namedMediatorDemoController
controller class, which uses theMediatR
Released a post titledInfoDemo
notification. When calling theMediatorDemoMethod
method, it creates aInfoDemo
A notification instance of typemediator
Publish this notification and record a log entry.
running example
1、Starting the Core Application
After launching the applicationMediatorDemoController
The controller will be registered and the constructor will be called to inject theIMediator
cap (a poem)ILogger<MediatorDemoController>
Dependencies.
2、Accessing Controller Methods
By accessing the/MediatorDemo
GET request to call theMediatorDemoMethod
Methods.
3、Create and publish notifications
existMediatorDemoMethod
method, create aInfoDemo
notification instance of type(information)
Publish the notice.
4、Disposal notice
When a notification is published, all notifications that implement theINotificationHandler<InfoDemo>
interface's handlers are called to handle notifications.
InfoDemoHandler
The processor receives the notification and records a log through the logger showing the received notification and its timestamp.
5、log
In the controller, the_logger.LogInformation
Records a log showing the notifications sent and their timestamps.
6、Return response
The controller method returns"Ok"
String indicating successful execution.
7、Expected results
summarize
With this simple example, it is possible to use theMediatR
library to publish and handle notifications, enabling in-process messaging. This approach helps decouple components and makes applications more modular and maintainable. The examples not only illustrate how to use theMediatR
to handle notifications, and also explains how to implement the notification handling pattern. By defining notifications and handlers, we can decouple different parts of the application, making the code clearer and easier to maintain.
ultimate
If you found this article helpful, why not support it with a like? Your support is what keeps me motivated to continue sharing my knowledge. If you have any questions or need further help, please feel free to leave a comment. You can also join the WeChat public number[DotNet Technician] community to share ideas and grow with other tech-loving peers!