Skip to content

Commit cb4da98

Browse files
Dispatching Domain Events right before DbContext SaveChanges() so side effects from additional Domain Event Handlers are included within the same transaction
1 parent a8733ac commit cb4da98

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

src/Services/Ordering/Ordering.Infrastructure/OrderingContext.cs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -237,10 +237,18 @@ void ConfigureCardTypes(EntityTypeBuilder<CardType> cardTypesConfiguration)
237237

238238
public async Task<int> SaveEntitiesAsync(CancellationToken cancellationToken = default(CancellationToken))
239239
{
240+
// Dispatch Domain Events collection.
241+
// Choices:
242+
// A) Right BEFORE committing data (EF SaveChanges) into the DB will make a single transaction including
243+
// side effects from the domain event handlers which are using the same DbContext with "InstancePerLifetimeScope" or "scoped" lifetime
244+
// B) Right AFTER committing data (EF SaveChanges) into the DB. will make multiple transactions.
245+
// You will need to handle eventual consistency and compensatory actions in case of failures.
246+
await _mediator.DispatchDomainEventsAsync(this);
247+
248+
249+
// After executing this line all the changes performed thought the DbContext will be commited
240250
var result = await base.SaveChangesAsync();
241251

242-
// Dispatch the Domain Events collection right after saving/committing data into the database
243-
await _mediator.DispatchDomainEventsAsync(this);
244252
return result;
245253
}
246254
}

0 commit comments

Comments
 (0)