public AggregateRoot Get <TAggregateRoot>(string aggregateRootId, IUnitOfWork unitOfWork, long maxGlobalSequenceNumber = long.MaxValue, bool createIfNotExists = false) { if (!EnabledFor <TAggregateRoot>()) { return(_aggregateRootRepository.Get <TAggregateRoot>(aggregateRootId, unitOfWork, maxGlobalSequenceNumber, createIfNotExists)); } var snapshot = _snapshotStore.LoadSnapshot <TAggregateRoot>(aggregateRootId, maxGlobalSequenceNumber); if (snapshot == null) { var aggregateRootInstance = _aggregateRootRepository.Get <TAggregateRoot>(aggregateRootId, unitOfWork, maxGlobalSequenceNumber, createIfNotExists); var checkedOutSequenceNumber = new AggregateRootInfo(aggregateRootInstance).SequenceNumber; if (maxGlobalSequenceNumber != long.MaxValue) { _snapshotStore.SaveSnapshot <TAggregateRoot>(aggregateRootId, aggregateRootInstance, maxGlobalSequenceNumber); } OnCommitted <TAggregateRoot>(aggregateRootId, unitOfWork, aggregateRootInstance, checkedOutSequenceNumber); return(aggregateRootInstance); } var preparedInstance = PrepareFromSnapshot <TAggregateRoot>(snapshot, maxGlobalSequenceNumber, unitOfWork, aggregateRootId); var sequenceNumberOfPreparedInstance = new AggregateRootInfo(preparedInstance).SequenceNumber; OnCommitted <TAggregateRoot>(aggregateRootId, unitOfWork, preparedInstance, sequenceNumberOfPreparedInstance); return(preparedInstance); }
public Model LoadModel(Type modelType = null) { Model model = null; //Try to load from the most recent snapshot var snapshotInfo = _snapshotStore.Snapshots.LastOrDefault(); if (snapshotInfo != null) { model = _snapshotStore.LoadSnapshot(snapshotInfo); model.SnapshotRestored(); } //If no snapshot present see if the first journal entry is of type ModelCreated if (model == null) { var firstJournalEntry = _commandStore.GetJournalEntries() .Take(1) .OfType <JournalEntry <ModelCreated> >() .SingleOrDefault(); if (firstJournalEntry != null) { modelType = firstJournalEntry.Item.Type; } if (modelType == null) { throw new InvalidOperationException("No model type present"); } model = (Model)Activator.CreateInstance(modelType); } var ctx = Execution.Begin(); //Replay commands foreach (var commandEntry in _commandStore.CommandEntriesFrom(model.Revision + 1)) { ctx.Now = commandEntry.Created; commandEntry.Item.Redo(ref model); ctx.Events.Clear(); model.Revision++; } model.JournalRestored(); return(model); }