using AutoMapper; using Kean.Domain.Order.Commands; using Kean.Domain.Order.Events; using Kean.Domain.Order.Repositories; using System.Threading; using System.Threading.Tasks; namespace Kean.Domain.Order.CommandHandlers { /// /// 修改订单命令处理程序 /// public sealed class ModifyOrderCommandHandler : CommandHandler { private readonly ICommandBus _commandBus; // 命令总线 private readonly IMapper _mapper; // 模型映射 private readonly IOrderRepository _orderRepository; // 订单仓库 /// /// 依赖注入 /// public ModifyOrderCommandHandler( ICommandBus commandBus, IMapper mapper, IOrderRepository orderRepository) { _commandBus = commandBus; _mapper = mapper; _orderRepository = orderRepository; } /// /// 处理程序 /// public override async Task Handle(ModifyOrderCommand command, CancellationToken cancellationToken) { if (command.ValidationResult.IsValid) { if (!await _orderRepository.IsOrderExist(command.Id)) { await _commandBus.Notify(nameof(command.Id), "订单不存在", command.Id, cancellationToken: cancellationToken); return; } // 更新订单 if (await _orderRepository.ModifyOrder(command.Id, command.Lines).ContinueWith(task => { if (task.Exception?.InnerException is RepositoryException ex) { task.Exception.Handle(_ => true); _commandBus.Notify(ex.Member.Key, ex.Message, ex.Member.Value, cancellationToken: cancellationToken).Wait(); return true; } return false; })) { return; } var @event = _mapper.Map(command); await _commandBus.Trigger(@event, cancellationToken); } else { await _commandBus.Notify(command.ValidationResult, cancellationToken: cancellationToken); } } } }