jasontaylordev / CleanArchitecture

Clean Architecture Solution Template for ASP.NET Core
MIT License
16.94k stars 3.64k forks source link

Domain events dispatched before save #1240

Closed fdugdale112 closed 1 week ago

fdugdale112 commented 3 weeks ago

Describe the bug Domain events are dispatched from the SavingChangesAsync in DispatchDomainEventsInterceptor. If the save fails, events are still dispatched. I have fixed this in my application by calling DispatchDomainEvents from an override of SavedChangesAsync instead of SavingChangesAsync.

To Reproduce Steps to reproduce the behavior:

  1. in any entity configuration add an index such as: builder.HasIndex(t => t.PropertyName).IsUnique();
  2. Save two entities with the same property value
  3. Any domain events on the second entity will still be dispatched
  4. See error

Expected behaviour Domain events shouldn't be dispatched when save fails

fdugdale112 commented 3 weeks ago

1241

jasontaylordev commented 1 week ago

There are pros and cons to dispatching domain events before or after saving changes. You've found one of the cons. You can read more here: https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-events-design-implementation#the-deferred-approach-to-raise-and-dispatch-events. I should create an ADR for this decision.

fdugdale112 commented 1 week ago

Ah, actually I think it would be better if both scenarios were supported. ideally the event handler should be able to decide whether the effect happens before, after or a combination. I don't think there is an easy way to achieve this with the current apis.

do you have any recommendations on how I can do this or any reason why I should avoid doing this?