xefiji
xefiji

Reputation: 367

Cross aggregate references: Can a command handler loop among a collection of aggregate ids, or can event handlers dispatch commands?

I need to remove a id from collections that are hold by multiple aggregates. Lets say i have a EmployeeAggregate, that contains a collection of Hobbies'id. The aggregate is event sourced.

Lets' say somewhere in the app someone, in a basic crud app handling a Hobbies table, deletes one Hobbie row. How can i reflect the changes in all the EmployeeAggregates ?

Frow now in the event store i have events concerning EmployeeAggregate, events concerning Hobbies (with the HobbieWasDeletedEvent), but nothing to make the EmployeeAggregate handle this HobbieWasDeletedEvent.

Some ideas of what i could do:

[EDIT]

Upvotes: 0

Views: 547

Answers (1)

CPerson
CPerson

Reputation: 1222

One approach is to use a saga/process to simulate a two phase commit to manage the following processes:

Assigning hobbies

  • User issues AssignHobby command to Employee aggregate. HobbyAssigned event is raised.
  • Saga receives HobbyAssigned and issues AddEmployee command to Hobby aggregate.
    • If the Hobby is active then EmployeeAdded event is raised
    • If the Hobby is inactive then the EmployeeNotAdded event is raised
  • Saga receives EmployeeNotAdded event and issues RemoveHobby command to Employee aggregate. HobbyRemoved event is raised.
    • Depending on how critical it is to never have an employee with an inactive Hobby, you can introduce a two-phase commit in this step as well, e.g. first request to add the Hobby and once the Hobby approves, then you can finalize the request with the Employee.

Remove hobbies

  • User issues Deactivate command to Hobby aggregate. Deactivated event is raised.
    • From this point forward, the Hobby aggregate will be marked as inactive. Any requests to add an employee will result in an EmployeeNotAdded event.
  • Saga receives Deactivated event. It loads the Hobby aggregate and issues a RemoveHobby command to each of the Employee aggregates assigned to the Hobby. Each raises a HobbyRemoved command.

Upvotes: 3

Related Questions