Referring Services in Aggregate Root

Hi all,

In my AR in order to run business process or validation I need information from some services, how do I inject these services into AR ? Is it even a good practice to ref services in AR?

Any advice would be greatly appreciated.

Thanks & Regards,

Jim

Hi Jim,

The easiest way is to add the service as a parameter of your command handler method:

@CommandHandler
void handle(SomeCommand command, YourService service) { ... }

In case you're using Spring the service is injected automatically. If not you need to register the service with the parameter resolver passed to the aggregate repository.

However, to answer your second question, it's often not a great idea to call services (or perform other potentially slow operations) from within your AR. The reason is that your aggregate instance is locked while it processes a command. Any command that takes a long time to process therefore severely limits the throughput of commands for that instance. Also the throughput is then a function of 'random' external factors like the latency of the service in question.

Often it's better to call the service before sending the command and add the result of the service invocation to the command. Note however that other commands may reach the AR instance while the service is being invoked, though in most cases that shouldn't matter.

Regards,
Rene

Hi Rene,

Thank you for your advice.

I couldn't agree more that ARs should retain their purity as much as possible by not introducing service dependencies and "enriching" commands comes to my mind of how, but sometimes I feel it's not practical to do so.

Let's say I have Invoice AR, upon creation I need to validate that inventory is available. So before submitting command I have to 1st query inventory last balance and put it in the command for the AR to validate against. I'm afraid the more data needed by AR the more bussiness process I have to move out from AR making it anemic.

Regards,
Setya