I've been working with DDD for a few months now and I've come across a few things I'm unsure of.
Take the simplistic example of adding a Product
to an Order
object. From our Controller, we'd have an int
passed via the UI which represents a Product
in the database. Which of the following two examples is correct (let me know if they're both wrong)?
Example One:
public class OrderController
{
// Injected Repositories
private readonly IProductRepository _productRepository;
// Called by UI
public void AddProduct(int productId)
{
Order order = ...; // Persisted Order
Product product = _productRepository.GetProduct(productId);
order.AddProduct(product);
}
}
The Controller instantiates the Product itself and adds it in via the method:
void AddProduct(Product product)
{
productList.Add(product);
}
Example Two:
public class OrderController
{
// Injected Repositories
private readonly IProductRepository _productRepository;
// Called by UI
public void AddProduct(int productId)
{
Order order = ...; // Persisted Order
order.AddProduct(productId, _productRepository);
}
}
The Order
domain model has the injected product repository passed to it and it gets the Product and adds it:
Product AddProduct(int productId, IProductRepository productRepository)
{
Product product = productRepository.GetProduct(productId);
productList.Add(product);
return product;
}
I've currently gone for the first example, because your Domain Model should never call a service method internally, however I've seen a few examples lately that use my second example and it does look tidy. It seems to me that Example One is verging on Anaemic. Example Two would move all the Product addition logic into the Domain Model itself.
Second one is horrible...
Adding a product to order should not have the repository on its signature since repository is not part of the domain.
I tend to go with the first one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With