/// <summary> /// 事件重演时,验证某个给定的事件是否有效 /// </summary> private void VerifyEvent(long currentVersion, AggregateRootEvent aggregateRootEvent) { if (aggregateRootEvent.Version <= DefaultVersion) { throw new EventSourcingException(string.Format("事件的版本号无效,必须大于等于{0}", DefaultVersion + 1)); } if (currentVersion == DefaultVersion) { if (aggregateRootEvent.Version != DefaultVersion + 1) { throw new EventSourcingException(string.Format("应用到聚合根上的第一个事件的版本必须为{0}.", DefaultVersion + 1)); } } else { if (aggregateRootEvent.AggregateRootId != _uniqueId) { var message = string.Format("不允许将其他聚合根(aggregateRootId:{0})的事件(详细信息:{1})应用到当前聚合根(aggregateRootId:{2}).", aggregateRootEvent.AggregateRootId, aggregateRootEvent.ToString(), _uniqueId); throw new EventSourcingException(message); } if (aggregateRootEvent.Version != currentVersion + 1) { var message = string.Format("不允许将版本为{0}事件应用到聚合根(aggregateRootId:{1}). 因为该聚合根的当前版本是{2}, 只有版本为{3}的事件才可以被应用到该聚合根.", aggregateRootEvent.Version, _uniqueId, currentVersion, currentVersion + 1); throw new EventSourcingException(message); } } }
/// <summary> /// 追加一个新的事件到当前聚合根维护的还未被持久化过的事件队列中 /// </summary> private void AppendEvent(AggregateRootEvent aggregateRootEvent) { if (_aggregateRootEvents == null) { _aggregateRootEvents = new Queue <AggregateRootEvent>(); } _aggregateRootEvents.Enqueue(aggregateRootEvent); }
public override bool Equals(object obj) { AggregateRootEvent aggregateRootEvent = obj as AggregateRootEvent; if (aggregateRootEvent == null) { return(false); } if (aggregateRootEvent.AggregateRootName == AggregateRootName && aggregateRootEvent.AggregateRootId == AggregateRootId && aggregateRootEvent.Version == Version) { return(true); } return(false); }
/// <summary> /// 验证给定的事件是否都属于同一个聚合根, T表示事件所属聚合根的类型 /// </summary> public static void AreEventsBelongtoSameAggregateRoot <T>(IEnumerable <AggregateRootEvent> evnts) where T : AggregateRoot { if (evnts == null) { return; } AggregateRootEvent previousEvent = null; foreach (var evnt in evnts) { if (evnt.AggregateRootType != typeof(T)) { throw new EventSourcingException(string.Format("检测到要保存的某个事件所属聚合根的类型与要求的聚合根类型不符,事件信息为:({0}),要求的聚合根类型为:({1})", evnt, typeof(T).FullName)); } if (previousEvent != null && previousEvent.AggregateRootId != evnt.AggregateRootId) { throw new EventSourcingException(string.Format("检测到要保存的两个事件不属于同一个聚合根,事件信息分别为:({0}),({1})", previousEvent, evnt)); } previousEvent = evnt; } }