refactoring and integration tests

This commit is contained in:
2022-10-10 04:02:46 +03:00
parent 28a6981001
commit ec54d2c255
15 changed files with 172 additions and 7 deletions
@@ -1,4 +1,6 @@
using Microsoft.EntityFrameworkCore;
using PracticeCalendar.Domain.Common;
using PracticeCalendar.Domain.Common.Interfaces;
using PracticeCalendar.Domain.Entities;
using System.Reflection;
@@ -6,9 +8,15 @@ namespace PracticeCalendar.Infrastructure.Persistence
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
private readonly IDomainEventService domainEventService;
public DbSet<Attendee> Atendees => Set<Attendee>();
public DbSet<PracticeEvent> PracticeEvents => Set<PracticeEvent>();
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IDomainEventService domainEventService)
: base(options)
{
this.domainEventService = domainEventService;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
@@ -17,7 +25,30 @@ namespace PracticeCalendar.Infrastructure.Persistence
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
public DbSet<Attendee> Atendees => Set<Attendee>();
public DbSet<PracticeEvent> PracticeEvents => Set<PracticeEvent>();
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
var events = ChangeTracker.Entries<EntityBase>()
.Select(x => x.Entity.DomainEvents)
.SelectMany(x => x)
.Where(domainEvent => !domainEvent.IsPublished)
.ToArray();
var result = await base.SaveChangesAsync(cancellationToken);
await DispatchEvents(events);
return result;
}
private async Task DispatchEvents(DomainEventBase[] events)
{
foreach (var @event in events)
{
@event.IsPublished = true;
await domainEventService.Publish(@event);
}
}
}
}