Beispiel #1
0
        Task TryGetAndCommitEvent(ProcessingCommand processingCommand, IProcessingCommandHandlerContext context)
        {
            var command        = processingCommand.Command;
            var commandType    = command.GetType();
            var commandId      = command.Id;
            var aggregateRoots = context.GetAggregateRoots().Where(a => a.GetUncommittedEvents().Any());

            if (aggregateRoots?.Count() == 1)
            {
                var aggregateRoot     = aggregateRoots.First();
                var aggregateRootType = aggregateRoot.GetType();
                var aggregateRootId   = aggregateRoot.Id;
                var eventStream       = new EventStream(
                    commandId,
                    aggregateRootType.FullName,
                    aggregateRootId,
                    aggregateRoot.Version + 1,
                    aggregateRoot.GetUncommittedEvents());
                var committingEvent = new CommittingEvent(eventStream, processingCommand, aggregateRoot);
                logger.LogDebug($"获取命令产生的事件成功,提交并发布事件!");
                return(eventCommitter.CommitAsync(committingEvent));
            }

            if (aggregateRoots?.Count() > 1)
            {
                logger.LogError($"命令处理超过 1 个聚合根。 [CommandType = {commandType}, CommandId = {commandId}, AggregateRoots = [{string.Join(" | ", aggregateRoots.Select(a => $"Type = {a.GetType()}, Id = {a.Id}"))}]]");
                return(processingCommand.OnQueueProcessedAsync(CommandExecutedStatus.Failed, "命令处理超过 1 个聚合根。"));
            }

            logger.LogWarning($"命令未处理任何聚合根,尝试获取是否已有事件产生并发布。 [CommandType = {commandType}, CommandId = {commandId}]");
            return(TryGetAndPublishEventStreamAsync(processingCommand));
        }