我有Category类,它具有子代属性。在创建类别时,我在构造函数中引发了事件CategoryCreated,该事件在BaseCategory中注册了此事件。另外,我在Category中有apply方法,该方法将事件应用于状态。
public class Category :BaseCategory
{
public Category(string id, TranslatableString name, DateTime timestamp)
{
Raise(new CategoryCreated(id, name, timestamp));
}
}
public override void Apply(DomainEvent @event)
{
switch (@event)
{
case CategoryCreated e:
this.Id = e.Id;
this.Name = e.Name;
break;
...
现在假设我想创建类别并为其添加子项。
var category = new Category("1","2",DateTime.UtcNow);
category.AddChild("some category", "name", DateTime.UtcNow);
foreach(var e in category.UncomittedEvents)
{
category.Apply(e);
}
添加孩子时,我将新创建类别的私有属性ParentId设置为父母的ID。
public void AddChild(string id, string name,DateTime date)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentNullException(nameof(id));
if (Children.Any(a => a.Id== Id))
throw new InvalidOperationException("Category already exist ");
Raise(new CategoryAdded(Guid.NewGuid().ToString(), this.Id/*parent id*/, name, DateTime.UtcNow));
}
public class CategoryAdded : DomainEvent
{
public CategoryAdded(string id, string parentId, string name, DateTime timestamp) {}
}
问题是,在应用事件时,父ID将为null,因为尚未应用事件,并且作为父ID传递的父ID属性为null:
new CategoryAdded(Guid.NewGuid().ToString(), this.Id /*parent id*/, name, DateTime.UtcNow)
设计错误在哪里?CategoryCreated事件应在何时何地引发?您将如何应对这种情况?
设计错误在哪里?
您的Raise(...)方法也应调用Apply。请记住,您的聚合负责维护一致状态。在聚合之外应用事件违反了该原则。
protected void Raise(DomainEvent @event)
{
this.Apply(@event);
this.UncomittedEvents.Add(@event);
}