Can not get Entity.Id on Events (always 0) #1124
Replies: 1 comment
-
Domain events are dispatched within the public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
{
DispatchDomainEvents(eventData.Context).GetAwaiter().GetResult();
return base.SavingChanges(eventData, result);
}
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
await DispatchDomainEvents(eventData.Context);
return await base.SavingChangesAsync(eventData, result, cancellationToken);
} In this design, domain events are dispatched before saving changes, so the Here's an example that illustrates the deferred approach to dispatching events, as described in .NET Microservices: Architecture for Containerized .NET Applications (see section The deferred approach to raise and dispatch events): // EF Core DbContext
public class OrderingContext : DbContext, IUnitOfWork
{
// ...
public async Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
// Dispatch Domain Events collection.
// Choices:
// A) Right BEFORE committing data (EF SaveChanges) into the DB. This makes
// a single transaction including side effects from the domain event
// handlers that are using the same DbContext with Scope lifetime
// B) Right AFTER committing data (EF SaveChanges) into the DB. This makes
// multiple transactions. You will need to handle eventual consistency and
// compensatory actions in case of failures.
await _mediator.DispatchDomainEventsAsync(this);
// After this line runs, all the changes (from the Command Handler and Domain
// event handlers) performed through the DbContext will be committed
var result = await base.SaveChangesAsync();
}
} In this example, when to dispatch domain events (before or after saving changes) depends on your specific requirements and the trade-offs you're willing to accept. |
Beta Was this translation helpful? Give feedback.
-
The value of Entity.Id on notification (Event Handlers) is always 0. How should I publish domain events after save changes on entity?
Beta Was this translation helpful? Give feedback.
All reactions