I have an Aggregate Root (AR1) that references another Aggregate Root (AR2) by Identity. i.e. as discussed here http://www.informit.com/articles/article.aspx?p=2020371&seqNum=4
Now in one of my methods in AR1 I need to access the full object of AR2 to perform a check. I have created a domain service called AR2DomainService and that is now being injected into the method of AR1. For example:
public class AR1
{
public Guid AR2Id;
public void DoSomething(IAR2DomainService, aR2DomainService)
{
AR2 ar2 = ar2DomainService.GetById(Ar2Id);
if(ar2.status != Status.OK)
//throw exception
//do some processing.
}
public bool DomSomething2(IAR2DomainService, ar2DomainService)
{
return ar2DomainService.DoSomething(Ar2Id);
}
}
Is this code ok?
As plalx points out, Domain Services aren't here to retrieve aggregates. What I would do is coordinate everything from the Application Service/Command Handler. It reads the associated Aggregate Root ID from
AR1
, and retrieves it through a Repository. Then it can extract relevant information fromAR2
and pass it as a parameter toAR1
's method. Note that the smaller this parameter, the better. Ideally you wouldn't passAR2
entirely but only a Value Object containing the minimum information needed (you don't want to be tempted to updateAR2
as part of a transaction inAR1
).