文章目录
一、轻松实现命令查询职责分离模式(CQRS)
1.自定义命令类
代码如下(示例):
class CustomCommand : IRequest<long>
{
public string Name { get; set; }
}
2.自定义实现IRequestHandler的类
CustomCommandHandler 通过泛型参数来关联CustomCommand
代码如下(示例):
class CustomCommandHandler : IRequestHandler<CustomCommand, long>
{
public Task<long> Handle(CustomCommand request, CancellationToken cancellationToken)
{
Console.WriteLine($"CustomCommand执行命令:{request.Name}");
return Task.FromResult(100L);
}
}
3.通过Send来调用CustomCommand
代码如下(示例):
var services = new ServiceCollection();
var assembly = typeof(Program).Assembly;
services.AddMediatR(assembly);
var serviceProvider = services.BuildServiceProvider();
var mediator = serviceProvider.GetService<IMediator>();
mediator.Send(new CustomCommand() {Name="testName" });
二、让领域事件处理更加优雅
1.自定义CustomEvent类继承INotification
代码如下(示例):
class CustomEvent: INotification
{
public string Name { get; set; }
}
2.自定义实现INotificationHandler的类
代码如下(示例):
CusotmEventHandler1 :
class CusotmEventHandler1 : INotificationHandler<CustomEvent>
{
public Task Handle(CustomEvent notification, CancellationToken cancellationToken)
{
Console.WriteLine($"CusotmEventHandler1 do sth:{notification.Name}");
return Task.CompletedTask;
}
}
CusotmEventHandler2 :
class CusotmEventHandler2 : INotificationHandler<CustomEvent>
{
public Task Handle(CustomEvent notification, CancellationToken cancellationToken)
{
Console.WriteLine($"CusotmEventHandler2 do sth:{notification.Name}");
return Task.CompletedTask;
}
}
3.通过Publish来调用实现了INotificationHandler的类
代码如下(示例):
var services = new ServiceCollection();
var assembly = typeof(Program).Assembly;
services.AddMediatR(assembly);
var serviceProvider = services.BuildServiceProvider();
var mediator = serviceProvider.GetService<IMediator>();
await mediator.Publish(new CustomEvent { Name = "testEventPublish" });
三、源码下载
总结
Send是1:1,只能发送一个命令对象,后面的后覆盖前面的。
Publish是1:*,只要实现了INotificationHandler接口的类都能接受到消息。

本文详细介绍了如何运用Mediator模式轻松实现命令查询职责分离(CQRS)。首先,通过自定义命令类和IRequestHandler实现命令处理;接着,利用领域事件让处理更加优雅,通过CustomEvent和INotificationHandler实现事件的发布与订阅。最后,提供了源码下载供读者参考。
1046

被折叠的 条评论
为什么被折叠?



