Exemplo n.º 1
0
    public async Task <TEntity> GetAsync <TEntity>(object id) where TEntity : class, IReadModelEntity
    {
        var entity = await _dbContext.Set <TEntity>().FindAsync(id);

        if (entity == null)
        {
            throw new EntityNotFoundException(typeof(TEntity), id);
        }

        return(entity);
    }
Exemplo n.º 2
0
    public async Task SaveAsync <TAggregateRoot>(TAggregateRoot aggregateRoot) where TAggregateRoot : AggregateRoot
    {
        var uncommittedEvents = aggregateRoot.PopUncommittedEvents();

        if (!uncommittedEvents.Any())
        {
            return;
        }

        var eventRecords = new List <EventRecord>();

        foreach (var uncommittedEvent in uncommittedEvents)
        {
            //Take snapshot every 10 version
            if (aggregateRoot.Version >= 10 && uncommittedEvent.AggregateVersion % 10 == 0)
            {
                if (aggregateRoot is IMementoOriginator mementoOriginator)
                {
                    var memento = mementoOriginator.GetMemento();

                    await _dbContext.Set <MementoRecord>().AddAsync(new MementoRecord
                    {
                        AggregateId      = memento.AggregateId,
                        AggregateVersion = memento.AggregateVersion,
                        Payload          = JsonSerializer.SerializeToDocument(memento, memento.GetType()),
                        Type             = memento.GetType().FullName
                    });
                }
            }

            eventRecords.Add(new EventRecord
            {
                AggregateId      = uncommittedEvent.AggregateId,
                AggregateVersion = uncommittedEvent.AggregateVersion,
                CreationTime     = DateTimeOffset.UtcNow,
                Type             = uncommittedEvent.GetType().FullName,
                Payload          = JsonSerializer.SerializeToDocument(uncommittedEvent, uncommittedEvent.GetType())
            });
        }

        await _dbContext.Set <EventRecord>().AddRangeAsync(eventRecords);

        await _dbContext.SaveChangesAsync();

        var tasks = uncommittedEvents.Select(e => _mediator.Publish(e)).ToList();
        await Task.WhenAll(tasks);
    }