我一直在学习CQRS/ES。查看我经常看到的小示例项目改变实体状态的事件。例如,如果我们看一下Order
聚合根:
public class Order : AggregateRoot {
private void Apply(OrderLineAddedEvent @event) {
var existingLine = this.OrderLines.FirstOrDefault(
i => i.ProductId == @event.ProductId);
if(existingLine != null) {
existingLine.AddToQuantity(@event.Quantity);
return;
}
this.OrderLines.Add(new OrderLine(@event.ProductId, @event.ProductTitle, @event.PricePerUnit, @event.Quantity));
}
public ICollection<OrderLine> OrderLines { get; private set; }
public void AddOrderLine(/*parameters*/) {
this.Apply(new OrderLineAddedEvent(/*parameters*/));
}
public Order() {
this.OrderLines = new List<OrderLine>();
}
public Order(IEnumerable<IEvent> history) {
foreach(IEvent @event in history) {
this.ApplyChange(@event, false);
}
}
}
public abstract class AggregateRoot {
public Queue<IEvent> UncommittedEvents { get; protected set; }
protected abstract void Apply(IEvent @event);
public void CommitEvents() {
this.UncommittedEvents.Clear();
}
protected void ApplyChange(IEvent @event, Boolean isNew) {
Apply(@event);
if(isNew) this.UncommittedEvents.Enqueue(@event);
}
}
when OrderLineAddedEvent
应用它会发生变异Order
通过添加新订单行。但我不明白这些事情:
- 如果这是正确的方法,那么所做的更改如何持久?
- 或者我应该以某种方式将事件发布到相应的处理程序
Order
?我如何在技术上实现这一点?我应该使用服务总线来传输事件吗?
我还在尝试 ES,所以这仍然是一种意见,而不是任何指导:)
在某个阶段,我看到了 Jan Kronquist 的这篇文章:http://www.jayway.com/2013/06/20/dont-publish-domain-events-return-them/
其要点是事件应该从域返回,而不是从域内调度。这确实引起了我的共鸣。
如果一个人要多拿一份传统的使用普通的面向持久性的存储库的方法应用层将处理事务和存储库访问。只需调用该域即可执行该行为。
此外,领域应该始终坚持持久性无知。让一个聚合根维护一个事件列表对我来说总是有点奇怪,而且我绝对不喜欢让我的 AR 继承一些公共基础。感觉不够干净。
因此,使用您拥有的资源将其组合在一起:
public OrderLineAddedEvent AddOrderLine(/*parameters*/) {
return this.Apply(new OrderLineAddedEvent(/*parameters*/));
}
在我的 POC 中,我也没有使用过IEvent
标记接口而只是一个object
.
Now the 应用层又恢复了对持久性的控制。
我有一个实验性的 GitHub 存储库:
- https://github.com/Shuttle/shuttle-recall-core
- https://github.com/Shuttle/shuttle-recall-sqlserver
我已经有一段时间没有时间查看它了,我知道我已经做了一些更改,但欢迎您查看。
基本思想是应用层将使用EventStore
/EventStream
以与管理聚合事件相同的方式应用层会使用一个Repository
. The EventStream
将应用于聚合。从域行为返回的所有事件都将添加到EventStream
之后它再次持续存在。
这将所有面向持久性的位保留在域之外。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)