Search code examples
domain-driven-designcqrsaggregaterootdomain-events

Can an aggregate be part of a domain-event?


Consider an aggregate with many properties. For example UserGroup. If I want to publish a UserGroupCreatedEvent I can do 2 things:

  1. duplicate the properties from the just created UserGroup to UserGroupCreatedEvent and copy their values. OR:

  2. Refer to the new UserGroup within the UserGroupCreatedEvent

In many examples, like Axon's Contacts App, I've seen property duplication. I wonder why, and if in real-world CQRS applications, this is not a lot of overhead, and developers choose to refer the aggregate instead.


Solution

  • An important property of domain events is that they are immutable. Bearing that in mind, the two possibilities you mention differ greatly:

    • Duplicating properties records their value at the time the UserGroup was created.
    • Referencing the UserGroup by ID just tells you that a UserGroup was created, but not the properties it had at the time. If the UserGroup has been deleted in the meantime, this means that the information is lost.

    Which properties you copy depends on just that difference. Do you need to be able to look up e.g. the name of a UserGroup at its creation time? Add it as a property. If not (and if it's not expected that it ever will be required), don't.

    Also, domain events have a global scope (i.e. they are meaningful outside of your BC), so you should include all information that clients outside of your BC need to make sense of the domain event.

    Note that attaching the whole aggregate root object to a domain event violates the immutability rule of domain events, so this is most probably a bad idea.