jasontaylordev/CleanArchitecture

Can not get Entity.Id on Events (always 0)

GhorbaniAli opened this issue · 1 comments

The value of Entity.Id on notification (Event Handlers) is always 0. How should I publish domain events after save changes on entity?

Domain events are dispatched within the DispatchDomainEventsInterceptor by overriding SavingChanges and SavingChangesAsync:

    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 Id has not yet been generated. If you need the Id to be available in your domain events, you could use a unique identifier (UID) for the entity, independent of the database-generated Id, or dispatch the domain events after saving changes. However, both approaches have challenges, such as handling transactional consistency and eventual consistency in case of failures.

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.