-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathEventDispatcherInterceptor.cs
More file actions
33 lines (25 loc) · 1.26 KB
/
Copy pathEventDispatcherInterceptor.cs
File metadata and controls
33 lines (25 loc) · 1.26 KB
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
using Microsoft.EntityFrameworkCore.Diagnostics;
namespace Clean.Architecture.Infrastructure.Data;
// Intercepts SaveChanges to dispatch domain events after changes are successfully saved
public class EventDispatchInterceptor(IDomainEventDispatcher domainEventDispatcher) : SaveChangesInterceptor
{
private readonly IDomainEventDispatcher _domainEventDispatcher = domainEventDispatcher;
// Called after SaveChangesAsync has completed successfully
public override async ValueTask<int> SavedChangesAsync(SaveChangesCompletedEventData eventData, int result,
CancellationToken cancellationToken = new CancellationToken())
{
var context = eventData.Context;
if (context is not AppDbContext appDbContext)
{
return await base.SavedChangesAsync(eventData, result, cancellationToken).ConfigureAwait(false);
}
// Retrieve all tracked entities that have domain events
var entitiesWithEvents = appDbContext.ChangeTracker.Entries<HasDomainEventsBase>()
.Select(e => e.Entity)
.Where(e => e.DomainEvents.Count != 0)
.ToArray();
// Dispatch and clear domain events
await _domainEventDispatcher.DispatchAndClearEvents(entitiesWithEvents);
return await base.SavedChangesAsync(eventData, result, cancellationToken);
}
}