Ejemplo n.º 1
0
        public async Task <ICommittedSnapshot> GetLatestSnapshotByIdAsync(Guid aggregateId)
        {
            var result = await _store.GetLatestSnapshotByIdAsync(aggregateId).ConfigureAwait(false);

            Verifier.CalledMethods |= EventStoreMethods.GetLatestSnapshotByIdAsync;

            return(result);
        }
Ejemplo n.º 2
0
        /// <inheritdoc />
        public async Task <TAggregate> GetByIdAsync <TAggregate>(Guid id) where TAggregate : Aggregate, new()
        {
            _logger.LogDebug($"Getting aggregate '{typeof(TAggregate).FullName}' with identifier: '{id}'.");

            var aggregate = _aggregateTracker.GetById <TAggregate>(id);

            _logger.LogDebug("Returning an aggregate tracked.");

            if (aggregate != null)
            {
                RegisterForTracking(aggregate);

                return(aggregate);
            }

            aggregate = new TAggregate();

            IEnumerable <ICommittedEvent> events;

            _logger.LogDebug("Checking if aggregate has snapshot support.");

            if (_snapshotStrategy.CheckSnapshotSupport(aggregate.GetType()))
            {
                if (aggregate is ISnapshotAggregate snapshotAggregate)
                {
                    int version  = 0;
                    var snapshot = await _snapshotStore.GetLatestSnapshotByIdAsync(id).ConfigureAwait(false);

                    if (snapshot != null)
                    {
                        version = snapshot.AggregateVersion;

                        _logger.LogDebug("Restoring snapshot.");

                        var snapshotRestore = new SnapshotRestore(snapshot.AggregateId, snapshot.AggregateVersion, snapshot.Data, snapshot.Metadata);

                        snapshotAggregate.Restore(snapshotRestore);

                        _logger.LogDebug("Snapshot restored.");
                    }

                    events = await _snapshotStore.GetEventsForwardAsync(id, version).ConfigureAwait(false);

                    LoadAggregate(aggregate, events);
                }
            }
            else
            {
                events = await _eventStore.GetAllEventsAsync(id).ConfigureAwait(false);

                LoadAggregate(aggregate, events);
            }

            if (aggregate.Id.Equals(Guid.Empty))
            {
                _logger.LogError($"The aggregate ({typeof(TAggregate).FullName} {id}) was not found.");

                throw new AggregateNotFoundException(typeof(TAggregate).Name, id);
            }

            RegisterForTracking(aggregate);

            return(aggregate);
        }