【发布时间】:2022-01-10 09:00:58
【问题描述】:
(从 Axon 论坛重新定位此讨论 https://discuss.axoniq.io/t/multi-entity-aggregate-best-practices-when-to-create-the-first-entity/3827)
Axon 文档建议通过 EventSourcingHandler 将新实体添加到聚合中……
来自:Multi-Entity Aggregates - Axon Reference Guide
实体的创建发生在其父级的事件源处理程序中。 因此,实体类上不可能有一个“命令处理构造函数”,就像聚合根一样。
(原文:注意“it's”中的撇号是错字)
但是您何时/在何处创建初始实体?
您的 GiftCard 聚合开始时没有实体。我们有一个类似的模型,但希望在创建聚合时创建一个初始实体。例如想象一下,如果新的礼品卡总是带有“默认”礼品卡交易。 你会在哪里做呢?
a) 在礼品卡的构造函数中:
public GiftCard(IssueCardCommand cmd) {
...
// problem: never gets replayed!
transactions.add(new GiftCardTransaction(/*defaults*/)
b) 在初始化事件处理程序中
public void on(CardIssuedEvent evt) { // initialize aggregate
// create the first entity
// gets replayed when the aggregate creation is replayed
transactions.add(new GiftCardTransaction(/*defaults*/)
}
c) 在事件处理程序中但通过触发事件
public void on(CardIssuedEvent evt) { // initialize aggregate
// fire the event to create the first entity
// problem: gets replayed twice: when the aggregate creation is replayed and the subsequent event is replayed!!?
apply(new CardRedeemedEvent(/*defaults*/);
}
d) 与 c 相同,但使用注解来防止重复播放:
public void on(CardIssuedEvent evt) { // initialize aggregate
// call a non-replayable method to fire the event
createFirstEntity();
}
@DisallowReplay
public void createFirstEntity() {
// The replay of this CardRedeemedEvent will create the first entity on replay,
// but the replay of the CardIssuedEvent will not, thanks to the @DisallowReplay... right??
apply(new CardRedeemedEvent(/*defaults*/);
}
【问题讨论】: