Still reading and learning about DDD and trying to apply it to a project I am working on. I am still trying to get by head around Aggregates and came across an interesting question.
Assume I have 2 Aggregates, 1 having an Account Entity for a root and the other a User Entity for a root.
An Account cannot be created without a User but a User can, that's why they both serve as the root of their own Aggregates. Note, their Aggregates include other entities but that's not important for my question.
Some business rules: 1) When an Account is created, it must be associated with a User. If the User does not exist, it must first be created.
2) When an Account is deleted, its associated User must also be deleted.
3) When a User is created, it does not need to be associated with an Account.
3) When a User is deleted, if it is associated with an Account, it must be deleted as well.
Since Account and User form their own aggregates, there will probably have their own Repositories. Which means the standard Add, Delete, Find, and Delete methods will be defined by each of these Repositories.
So given these scenarios, what is the best way to accomplish the following: 1) When an Account is created, I figured I would invoke a Method on its User's property to validate the User ensuring it exists. Is this right?
2) When an Account is deleted, how do I also delete its associated User. From the Account Repoistory? But would that not just duplicate code in the User Repository? Or can Repositories reference and invoke one another?
3) When a User is deleted, what's the best way to determine if it associated with an Account and delete it as well without code duplication (probably similiar to the 2nd question).
I read somewhere that if logic crosses two Entities or Aggregates, consider using a Service. But I am not satisifed with that since what is stopping a client (assuming the API will be evolved and user with other presentations in the future) from bypassing the Service and simply invoking the Repositories?
Update 1:
Just realized that this is probably a related question: How should I enforce relationships and constraints between aggregate roots?