-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
AppDbContext.cs
37 lines (28 loc) · 1.24 KB
/
AppDbContext.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using Clean.Architecture.Core.ContributorAggregate;
namespace Clean.Architecture.Infrastructure.Data;
public class AppDbContext(DbContextOptions<AppDbContext> options,
IDomainEventDispatcher? dispatcher) : DbContext(options)
{
private readonly IDomainEventDispatcher? _dispatcher = dispatcher;
public DbSet<Contributor> Contributors => Set<Contributor>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
int result = await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// ignore events if no dispatcher provided
if (_dispatcher == null) return result;
// dispatch events only if save was successful
var entitiesWithEvents = ChangeTracker.Entries<HasDomainEventsBase>()
.Select(e => e.Entity)
.Where(e => e.DomainEvents.Any())
.ToArray();
await _dispatcher.DispatchAndClearEvents(entitiesWithEvents);
return result;
}
public override int SaveChanges() =>
SaveChangesAsync().GetAwaiter().GetResult();
}