我正在开发一个事件源CQRS 实现,在应用程序/域层中使用 DDD。我有一个看起来像这样的对象模型:
public class Person : AggregateRootBase
{
private Guid? _bookingId;
public Person(Identification identification)
{
Apply(new PersonCreatedEvent(identification));
}
public Booking CreateBooking() {
// Enforce Person invariants
var booking = new Booking();
Apply(new PersonBookedEvent(booking.Id));
return booking;
}
public void Release() {
// Enforce Person invariants
// Should we load the booking here from the aggregate repository?
// We need to ensure that booking is released as well.
var booking = BookingRepository.Load(_bookingId);
booking.Release();
Apply(new PersonReleasedEvent(_bookingId));
}
[EventHandler]
public void Handle(PersonBookedEvent @event) { _bookingId = @event.BookingId; }
[EventHandler]
public void Handle(PersonReleasedEvent @event) { _bookingId = null; }
}
public class Booking : AggregateRootBase
{
private DateTime _bookingDate;
private DateTime? _releaseDate;
public Booking()
{
//Enforce invariants
Apply(new BookingCreatedEvent());
}
public void Release()
{
//Enforce invariants
Apply(new BookingReleasedEvent());
}
[EventHandler]
public void Handle(BookingCreatedEvent @event) { _bookingDate = SystemTime.Now(); }
[EventHandler]
public void Handle(BookingReleasedEvent @event) { _releaseDate = SystemTime.Now(); }
// Some other business activities unrelated to a person
}
到目前为止,根据我对 DDD 的理解,Person 和 Booking 都是单独的聚合根,原因有两个:
- 有时业务组件会从数据库中单独提取 Booking 对象。(即,已被释放的人由于信息不正确而修改了先前的预订)。
- 每当需要更新 Booking 时,Person 和 Booking 之间不应存在锁定争用。
另一个业务要求是一个人一次不能多次进行预订。因此,我担心在读取端查询查询数据库,因为那里可能存在一些不一致(由于使用 CQRS 并具有最终一致的读取数据库)。
是否应该允许聚合根通过 id 查询事件源后备存储中的对象(根据需要延迟加载它们)?还有其他更有意义的实施途径吗?