public override async Task <TAggregate> LoadById(string aggregateId)
        {
            Argument.StringNotEmpty(aggregateId, nameof(aggregateId));

            AggregateSnapshot snapshot = await _snapshotStore.GetSnapshot(aggregateId);

            if (snapshot == null)
            {
                return(await base.LoadById(aggregateId));
            }

            var aggregate = new TAggregate {
                Id = aggregateId
            };

            aggregate.Restore(snapshot);

            var stream = await _eventStore.GetStreamAsync(aggregateId, snapshot.Version + 1); //todo

            aggregate.Version = stream.Version;
            aggregate.Reel(stream.Events);
            aggregate.SetStatus(_eventStore.FirstEventIndex, stream.IsClosed);

            return(aggregate);
        }
        public override async Task Save(TAggregate aggregate)
        {
            await base.Save(aggregate);

            int currentVersion = aggregate.Version;

            if (currentVersion > 0 && currentVersion % _interval == 0)
            {
                AggregateSnapshot snapshot = aggregate.MakeSnapshot();
                await _snapshotStore.SaveSnapshot(snapshot);
            }
        }
        public BsonDocument Serialize(AggregateSnapshot snapshot)
        {
            return new BsonDocument()
            {
                { AggregateIdElement, snapshot.AggregateId },
                { AggregateTypeElement, snapshot.AggregateType.AssemblyQualifiedName },
                { VersionElement, snapshot.Version },
                { TimestampElement, snapshot.Timestamp },

                { StateTypeElement, snapshot.State.GetType().AssemblyQualifiedName },
                { StateElement, _dataSerializer.Serialize(snapshot.State) },
            };
        }
        internal static void Restore(this IAggregateRoot aggregate, AggregateSnapshot snapshot)
        {
            if (aggregate.Id != snapshot.AggregateId)
            {
                throw new InvalidOperationException("Invalid aggregateId in snapshopt.");
            }

            if (aggregate.GetType() != snapshot.AggregateType)
            {
                throw new InvalidOperationException("Trying to restore aggregate with wrong snapshot type.");
            }

            if (aggregate.State.GetType() != snapshot.State.GetType())
            {
                throw new InvalidOperationException("Trying to restore aggregate with wrong snapshot state type.");
            }

            aggregate.State   = snapshot.State;
            aggregate.Version = snapshot.Version;
        }
Esempio n. 5
0
 public async Task SaveSnapshot(AggregateSnapshot snapshot)
 {
     await GetCollection().ReplaceOneAsync(_snapshotSerializer.GetIdFilter(snapshot.AggregateId), _snapshotSerializer.Serialize(snapshot), MockUpsert);
 }