MediatR是.net下的一个实现消息传递的库,简洁高效,它采用
中介者设计模式,通过进程内消息传递机制,进行请求/响应、命令、查询、通知和事件的消息传递,可通过泛型来支持消息的智能调度,用于领域事件中。
实践:
1 // Add services to the container.
2 builder.Services.AddMediatR(cfg =>
3 {
4 cfg.RegisterServicesFromAssembly(typeof(Program).Assembly);
5 });
public record Information (string Info) : INotification;
public class InformationHandler(ILogger<InformationHandler> _logger) : INotificationHandler<Information>
{
public Task Handle(Information notification, CancellationToken cancellationToken)
{
_logger.LogInformation($"InformationHandler Received: {notification}. {DateTimeOffset.Now}");
return Task.CompletedTask;
}
}
[ApiController]
[Route("[controller]")]
public class MediatorController(ILogger<MediatorController> _logger,
IMediator mediator) : ControllerBase
{
[HttpGet(Name = "Test")]
public string Test()
{
var information = new Information("This is a message from controller.");
mediator.Publish(information);
_logger.LogInformation($"{DateTimeOffset.Now} : MediatorController Send: {information}.");
return $"Ok";
}
}
OK了,可以运行测试下了,结果如下: