Handling events applied by entities in an aggregate

Hello everyone,

I have an aggregate containing some @AggregateMember annotated entities. From my entities’ @CommandHandler annotated methods I apply some events.

I would like to apply some kind of summary event from my aggregate whenever a entity applies an event. How can I achieve that in Axon Framework?

Currently I pass some kind of callback to the entities. After appliying an event the entities have to call .andThen(callback). That works, but I don’t want the entities to be responsible for calling the callback.

I want the aggregate to handle the events it is interested in to apply a summary event.

One idea I have is to have an event handler in the aggregate which is not used for rebuilding the aggregate state and which allows to apply additional events… the approach is similar to ApplyMore.andThen, but the event applier does not have to know that something in the aggregate should happen after applying an event.

Is there any techinque I can use in Axon Framework?

Thanks for helping me.

Best regards
Oliver

Ok, I found out that Axon already supports this scenario: Applying Events from Event Sourcing Handlers :+1:

It works, but I have a problem with the invocation order of the Event Sourcing Handlers. In my scenario the Aggregate’s Event Sourcing Handler is invoked before the Entity’s Event Sourcing Handler. Is it possible to fine-tune that behaviour?

This seems to be the intended behaviour:

When an entity (including the aggregate root) applies an event, it is handled by the aggregate root first, and then bubbles down through every @AggregateMember annotated field to all its containing child entities.

Source: Event Sourcing Handlers in Entities

Anyway, I found a solution (workaround?):

final AnnotatedAggregate<?> currentScope = Scope.getCurrentScope( );
currentScope.andThenIf( AggregateLifecycle::isLive, this::doSomtehing );

With this code I can achieve that doSomething is invoked after the Entity’s Event Sourcing Handler is invoked. Therefore doSomething can see the state changes peformed by the entity.

Is this a valid solution or do you see any problems? If it’s a valid usecase it would be great to have some better API like AggregateLifecycle#doAfterEventsHandled (can’t find a better naming for the moment).

I highly appreciate any feedback by the developers/community. My solution seems to work, but I wonder if it’s the intended way to do so…

I would build a projection to account for these kinds of summary events. There might be some data/code duplication, but it keeps them loosely coupled. In my opinion, you should do as little as possible in an aggregate. It seems like this is something that an event processor can do.