title: Repository and Aggregate Roots in Domain Driven Design
body: <p>I am building a notification system, where I have users that can create subscriptions which define when a notification will be delivered to them and by which endpoint. I have established that a User is an Aggregate Root, and will have a Repository for them. I am having a bit of trouble wrapping my head around this concept though. From my understanding, only Aggregate Roots should be pulled from a Repository.</p>
  
  <p>Let's say I have a User</p>
  
  <pre><code>public class User
  {
      public ICollection&lt;Subscription&gt; Subscriptions {get; set;}
      public ICollection&lt;Endpoint&gt; Endpoints {get; set;}
  }
  </code></pre>
  
  <p>This User has a collection of Subscriptions and Endpoints. Both of these are Entities themselves, as their contents can change without it being a different object. For instance, both these entities can be enabled/disabled. They cannot exist outside the context of a User, as only a User can create a Subscription or an Endpoint.</p>
  
  <p>My Subscription also contains a reference to an Endpoint, as this Subscription needs to know where to deliver. </p>
  
  <pre><code>public class Subscription
  {
      public ICollection&lt;Endpoint&gt; Endpoints {get; set;}
  }
  </code></pre>
  
  <p>So, as I have defined the User as the Aggregate Root, I now have a UserRepository for persisting my users. Any modifications to an Endpoint or a Subscription would be done within the context of a User being the Aggregate Root. This makes sense to me. But what if I want to retrieve a list of Subscriptions which meet a set of Criteria. The system which handles triggering a notification will receive an event, and need to query for a set of Subscriptions that are relevant to that event. The event is not user based, as multiple Users can have Subscriptions which are valid for this event. Would I put a method on my UserRepository which returns these Subscriptions? Or would I create a SubscriptionRepository? If I create the SubscriptionRepository, would that not mean that a Subscription is an Aggregate Root as well? If the answer to that question is yes, then does my design violate the concept of an AggregateRoot since both User and Subscription contain a reference to an Endpoint entity?</p>