Implementing Repository in DDD – Part 1

Implementing Repository is fairly staright forward in DDD. There are generally two styles of implementation,
1. aggregate-dedicated repository and
2. generic repository.

An aggregate-dedicated repository will have a method per command or query; while, Generic repository will have a standard interface for every Aggregate. However, in both cases, the repository is suppose to operate at the aggregate-root level. This post will demostrate implementation of an aggregate-dedicated repository,

In your domain layer,
public class Order: IAggregateRoot
public Order(IOrderRepository repository)
{ ..}

public void Order(PlaceOrderCommand command)
public Order Get(Guid id)
return repository.Single(id);

public IList<Order> GetOrdersByCustomer(Guid customerId)
return repository.Where(o=>o.CustomerId = customerId);

Application Layer,

public class OrderService
public void PlaceOrder(PlaceOrderCommand command)
var Order = new Order(new OrderRepository());

The Application Layer uses dependency injection to inject an instance of the repository that the aggregate uses. The aggregate-root then calls the repository internally to persists the data and retrieve data.

In this style of implementation, a dedicated repository designed for each aggregate-root. This means a little more coding up-front compared to generic repositories, as there is one repository per aggregate. Writing unit-tests might be a little more difficult. But over all, the simplicity and flexibility that this implementation brings is huge and depending on your taste, choice of tech-stacks and data-access needs it might be a very good fit for you. Definitely worth a consideration.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s