Hey @Daniel_S, and welcome to the forum!
Wherever you’re interacting with Axon Framework’s infrastructure components, I would foremost recommend to use the interface.
Thus, when directly interacting with an aggregate repository (which is similarly not a necessity), I would use the Repository
.
Concerning the UnitOfWork
issues, that’s because Axon Framework expects an active UnitOfWork
whenever any type of message handling function’s invoked. Similarly, Axon will generate a UnitOfWork
when messages are dispatched.
In essence, the UnitOfWork
manages the complete lifecycle of messages and thus is the cornerstone of the Framework’s functionality.
The aggregate is a specialized message handler, as it’s a group of handlers together.
So, when dealing with your Aggregate, Axon expects an active UnitOfWork
.
You can, indeed, start the UnitOfWork
manually.
However, if you use Axon’s message buses instead of invoking the Repository
directly, you are ensured a UnitOfWork
is started and dealt with as intended.
If you want to take CQRS a step further, you can thus dispatch a command on the CommandGateway
/CommandBus
that either (1) is handled by a function invoking the Repository
or (2) directly invokes an annotated command handler on the Aggregate.
Simply put, you can do something like this:
Option1
public class CommandHandlingComponent {
private Repository<SomeAggregate> repository;
@CommandHandler
public void handle(SomeCommand command) {
repository.load(command.getAggregateId())
.execute(yourAggregate -> yourAggregate.handle(command));
}
}
Option2
public class SomeAggregate {
@CommandHandler
public void handle(SomeCommand command) {
// your command handling task here
}
}
In doing either of the above, you’ve told Axon Framework firstly to dispatch a command on the bus and thus initiate a UnitOfWork
.
Then the CommandBus
is concerned with routing the message (so you don’t have to), invoking the @CommandHandler
annotated method.
In the case of option1, you would thus still work with the Repository
directly (if desired) and are ascertained a UnitOfWork
is active (and managed correctly!).
When using option2, the same guarantee is in place, although that time around Axon Framework will invoke the Repository
for you.