简体   繁体   English

使用 CQRS 和事件溯源的状态模式

[英]State Pattern With CQRS And Event Sourcing

I am using CQRS with Event Sourcing and I am trying to use the state pattern with my aggregate root.我正在将 CQRS 与事件溯源一起使用,并且我正在尝试将状态模式与我的聚合根一起使用。

I currently have a product domain model with a couple methods called Create() and CreateSubscription like below.我目前有一个产品域模型,其中包含一些名为 Create() 和 CreateSubscription 的方法,如下所示。

public static void Create(string name){        
    When(new ProductCreatedEvent { Name = name});
}

public void CreateSubscription(string name){        
    if(_productState.CanCreateSubscription()){
        When(new SubscriptionCreatedEvent { Name = name});
    }        
}

Then I have the private methods that actually sets the values like below.然后我有私有方法来实际设置如下值。

private void OnCreated(ProductCreatedEvent e){
     _name = e.Name;
}

private void OnSubscriptionCreated(SubscriptionCreatedEvent e){
     _subscriptions.Add(Subscription.Create(e.Name));
}

When I have used the state pattern before using DDD the logic was moved into the state class but because I am using event sourcing I need to call the When method which is in a base class which then invokes my private 'On' methods which actually sets the values.当我在使用 DDD 之前使用状态模式时,逻辑被移到状态类中,但是因为我使用事件源,我需要调用位于基类中的 When 方法,然后调用我的私有“On”方法,该方法实际上设置值。

I was wondering how to move that logic into my state class, otherwise at the moment my state class only has 'Can' methods on it and not the actual implementation code.我想知道如何将该逻辑移动到我的状态类中,否则目前我的状态类上只有“Can”方法,而不是实际的实现代码。

Can you not just pass things into _productState?你不能只是把东西传给_productState吗?

private void OnSomeEvent(SomeEvent e){
    _productState.Something(); // pass in e?
}

For example:例如:

public void CreateSubscription(string name){        
    _productState.CreateSubscription(name); 
}

public class ProductState
{
    public void CreateSubscription(string name)
    {
        if (this.CanCreateSubscription())
        {
            _subscriptions.Add(Subscription.Create(name));
        }
    }
}

Or或者

public void OnSomeEventThatMeansYouCanCreateASubscription(string name)
{   
    _productState.EnableCreateSubscription(name);     
}

public void OnSomeEventThatNeedsToCheckTheState(string name)
{   
    if (_productState.CanCreateSubscription())     
        _subscriptions.Add(Subscription.Create(name));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM