예제 #1
0
        public async Task <TAggregate> GetAsync(Guid id)
        {
            var events = new List <AggregateEvent>();
            StreamEventsSlice currentSlice;
            long nextSliceStart = StreamPosition.Start;
            var  streamName     = EventStoreExtensions.GetStreamName <TAggregate>(id);
            int  batchSize      = 100;

            do
            {
                currentSlice = await _connection
                               .ReadStreamEventsForwardAsync(streamName, nextSliceStart, batchSize, false);

                nextSliceStart = currentSlice.NextEventNumber;
                events.AddRange(currentSlice.Events.Select(x => (AggregateEvent)x.DeserializeEvent()));
            } while (!currentSlice.IsEndOfStream);
            var aggregate = _factory.Create <TAggregate>(events);

            return(aggregate);
        }
예제 #2
0
        public async Task SaveAsync(AggregateRoot aggregate)
        {
            var commitId = Guid.NewGuid();
            var events   = aggregate.UncommittedEvents;

            if (events.Any() == false)
            {
                return;
            }

            var streamName      = EventStoreExtensions.GetStreamName <TAggregate>(aggregate.AggregateId);
            var originalVersion = aggregate.Version;// - events.Count();
            var expectedVersion = originalVersion == 0 ? ExpectedVersion.NoStream : originalVersion - 1;
            var commitHeaders   = new Dictionary <string, object>
            {
                { "CommitId", commitId },
                { "AggregateClrType", aggregate.GetType().AssemblyQualifiedName }
            };
            var eventsToSave = events.Select(e => e.ToEventData(commitHeaders)).ToList();
            await _connection.AppendToStreamAsync(streamName, expectedVersion, eventsToSave);

            aggregate.MarkChangesAsCommitted();
        }