.NET Core MediatR订阅发布
前言
上一章主要通过MediatR进行职责分离,本章将通过MediatR使用订阅发布
- Publish 此方法会将消息发布到内存队列,如果有任何订阅者订阅,此消息自行处理业务.
在我们开发中可能会存在一个场景,当我添加完某条数据或者说当我执行完一些操作后我需要进行发个邮件通知或者短信通知等等.
Notification
OrderCreatedEvent
所有的事件都需要继承INotification接口
public class OrderCreatedEvent: INotification { public string UserId { get; set; } public OrderCreatedEvent(string orderId) { this.UserId = orderId; } }
OrderCreatedDomainEventHandler在这其实可以进行实现广播也就是实现多消费者去订阅.所有消息处理器都需要继承INotificationHandler接口
public class OrderCreatedDomainEventHandler : INotificationHandler<OrderCreatedEvent> { private readonly ILogger _logger; public OrderCreatedDomainEventHandler(ILogger<OrderCreatedDomainEventHandler> logger) { _logger = logger; } public Task Handle(OrderCreatedEvent notification, CancellationToken cancellationToken) { _logger.LogInformation($"Order has found by userid id: {notification.UserId} from publisher"); return Task.CompletedTask; } }
CreateOrderCommandHandler 通过我们的订单处理器创建完订单,通过Mediator进行发布消息
public class CreateOrderCommandHandler : IRequestHandler<CreateOrderRequestModel, string> { private readonly IMediator _mediator; public CreateOrderCommandHandler(IMediator mediator) { this._mediator = mediator; } public async Task<string> Handle(CreateOrderRequestModel request, CancellationToken cancellationToken) { //do something... await _mediator.Publish(new OrderCreatedEvent(request.UserId), cancellationToken); return request.UserId; } }
Reference
https://github.com/hueifeng/BlogSample/tree/master/src/CQRSMediatR
No comments:
Post a Comment