Domain services

Hi there,

I’ve been using Axon to create annotated aggregate roots and annotated sagas. Everything’s working well.

Within my sagas, events are consumed and commands are issued to aggregates as you would expect.

However, in one of my sagas, I want to issue a command to something that is not an aggregate root - it’s a stateless object which performs a calculation and raises an event when the calculation is complete. From what I can see in CQRS, this kind of stateless object is a “domain service” (please correct me if I’m mistaken).

I was able to implement my domain service in Axon, but I had to do some odd things like pass an instance of an event bus in the command that kicks off the domain service. What I wanted to do was implement my domain service as a kind of cut-down Saga that doesn’t have any state (so that it automatically has an event bus and other handy stuff).

Am I missing a trick? Is there some easier way to implement a domain service in Axon? Or are domain services intentionally missing from Axon because they’re in some way “bad”?

Advice appreciated :slight_smile:


Hi Renny,

why don’t you simply configure a field on your domain service that contains the Event Bus you want to publish changes on? If you use Spring, you can also add the Event Bus as a parameter to your @CommandHandler method. Axon will automatically inject the Event Bus when the command handler is invoked.

One piece of advice: use the Unit of Work to publish events on the Event Bus. That way, you guarantee proper ordering of events in handlers, and make sure that events are only published when the handler returns successfully. Either add a parameter of type UnitOfWork to your @CommandHandler method or use CurrentUnitOfWork.get() to get a reference to it. Then UnitOfWork.publishEvent(…) to schedule the event for publication.