Chris
Chris

Reputation: 257

Domain Driven Design related aggregate roots and UI retrieval

I'm trying to grasp more and more of Domain Driven Design and follow best practices. So far this is my understanding:

My questions are:

If I have more than one aggregate related to each other, say Orders And Product Categories.

How should the application service handle the retrieval of an order and related product category?

Should the service have a reference to each repository of an order and product category, retrieve the order first, then retrieve the product category, and finally fill out a data transfer object referencing the information from both?

Something like this:

public OrderDto GetOrder(int id)
{
    var order = _orderRepo.GetById(id);

    var productCategory = _categoryRepo.GetById(order.ProductCategoryId);

    return new OrderDto 
                  { 
                     CustomerName = order.CustomerName, 
                     ProductCategoryName = productCategory.Name,
                     *..etc..*
                  };
}

Or is it over kill to keep the roots that decoupled if they are tightly related?

Or should the UI be making the calls to independent services for the complete picture?

Upvotes: 0

Views: 793

Answers (2)

hashem salim
hashem salim

Reputation: 1

Using the CQRS pattern in your application seems an option. The pattern fits well with DDD because it helps us in this kind of situation where we need a different mechanism for writing and reading data, you can read more about CQRS in this article https://martinfowler.com/bliki/CQRS.html, so if you want to retrieve data for the purpose of display you don't need to get all the aggregate roots because invariance of the entity can't be invalid when reading data i.e the entity state is not changing.

Upvotes: 0

Yugang Zhou
Yugang Zhou

Reputation: 7283

There are some situations you may have to break the rules according to Reasons to break the rules section

The first one of them is presetation convenience, it's not a big deal when you just neeed to display one Order at a time, but the solution you mentioned causes N + 1 query problem if you need to list Order s.

Alternative solution is stick to the rule and use your persistence object for rendering ui(in list Order case) if you want to seperate(or have already seperated) your domain models from persistence infrastructure, some discussion can be found here.

Upvotes: 1

Related Questions