I was implementing this yesterday, and suddenly got the impression that something didn’t “feel right”. So I decided to check how this information was made available to entities in some of the projects that I have access to.
In Axon 2, I have refactored the domain model so that Axon doesn’t interfere with the model in any other way than helping support the registration and handling of Events. Adding a method to get hold of the aggregate identifier via a method would do the contrary.
Therefore, if you need any information about the aggregate root in your entities, just make sure that information is passed (e.g. via the constructor or as extra parameter on method calls) to the entity. Just do it in the way you would have done it when not using Axon.
what I mean is that when the aggregate root creates an entity, it should simply provide the aggregate identifier in the constructor.
For example:
@EventHandler
public void handle(SomeEventThatCreatesAnEntity event) {
this.someEntity = new SomeEntitiy(this.aggregateIdentifier);
}
in the Entity itself, you add a field that stores the aggregate identifier. That field could even be final.
I don’t think there is a necessity for any Axon magic to happen here. But of course, I could be mistaken ;-).