如何让 Cirqus 停止自动创建新实例?

How can I make Cirqus stop automatically creating new instances?

我有一个包含一些事件和命令的聚合根。其中一个命令是 CreateCommand。该命令应创建一个具有给定 ID 的新聚合根。每隔 event/command 应该只更新现有的聚合根,如果具有给定 ID 的聚合根不存在 则失败 .

如何让 Cirqus 以这种方式工作?

这是我配置 CommandProcessor 的方式:

                var commandProcessor = CommandProcessor
                    .With()
#if DEBUG
                    .Logging(l =>
                    {
                        if (_useConsoleForLogging)
                        {
                            l.UseConsole(Logger.Level.Debug);
                        }
                        else
                        {
                            l.UseDebug(Logger.Level.Debug);
                        }
                    })
#endif
                    .EventStore(e => e.UseSqlServer(_connectionString, _eventsTableName))
                    .EventDispatcher(e => e.UseViewManagerEventDispatcher(viewManagers))
                    .Create();

这是 CreateCommand:

    public class CreateCommand : ExecutableCommand
    { 
        public CreateCommand()
        {
            CreatedGuid = Guid.NewGuid();
        }

        public Guid CreatedGuid { get; }

        public override void Execute(ICommandContext context)
        {
            var root = context.Create<MyAggregateRoot>(CreatedGuid.ToString());
        }
    }

当然,此 CreateCommand 包含更多代码,这些代码会发出一些事件以立即更新已创建实例的某些属性,但我删除了它们,因为它们对这个问题。

您可以通过使用 ExecutableCommand 实现您自己的更新命令来做到这一点 - 您可以将其命名为 UpdateCommand

它可能看起来像这样:

public abstract class UpdateCommand<TAggregateRoot>
{
    readonly string _aggregateRootId;
    protected UpdateCommand(string aggregateRootId)
    {
        _aggregateRootId = aggregateRootId;
    }

    public override void Execute(ICommandContext context)
    {
        var instance = context.Load<TAggregateRoot>(_aggregateRootId);

        Update(instance);
    }

    public abstract void Update(TAggregateRoot instance);
}

然后从 UpdateCommand 派生的所有命令如果试图处理不存在的实例,都会遇到异常。

类似地,您可以 确保创建 使用 CreateCommand 基础 class 将使用 ICommandContextCreate<TAggregateRoot> 方法以确保不会意外地处理现有实例。