Domain events should be published utill there are no more left
A reference .NET application implementing an eCommerce site
Brought to you by:
jobily
Originally created by: bin-jump
Current implementation of eShop.Ordering.Infrastructure.MediatorExtension.DispatchDomainEventsAsync (github.com)
will check tracked entities and publish all domain event those entices hold once, which triggers domain event handlers to handle published events.
However, in real world applications, domain event handlers might also cause new domain events generated, and in current implementation new created domain events will be ignored.
I wrote this implementation that will keep publishing created domain events from tracked entires recursively, utill there are no more left. Please consider.
static class MediatorExtension
{
public static async Task DispatchDomainEventsAsync(this IMediator mediator, OrderingContext ctx)
{
bool remains = true;
while(remains) {
var publishedCount = await DispatchDomainEventsRecursivelyAsync(mediator, ctx);
remains = publishedCount > 0;
}
}
private static async Task<int> DispatchDomainEventsRecursivelyAsync(this IMediator mediator, OrderingContext ctx)
{
var domainEntities = ctx.ChangeTracker
.Entries<Entity>()
.Where(x => x.Entity.DomainEvents != null && x.Entity.DomainEvents.Any());
var domainEvents = domainEntities
.SelectMany(x => x.Entity.DomainEvents)
.ToList();
int count = domainEvents.Count;
domainEntities.ToList()
.ForEach(entity => entity.Entity.ClearDomainEvents());
foreach (var domainEvent in domainEvents)
await mediator.Publish(domainEvent);
return count;
}
}
Would be happy to create the PR.