title: Architectural concerns: Fluent NHibernate, The Repository pattern and ASP.NET MVC
body: <p>I've just started a new project and have naturally opted to use a lot of new tech.</p>
  
  <p>I'm using (Fluent) NHibernate, ASP.NET MVC 3 and am trying to apply the Repository pattern.</p>
  
  <p>I've decided to seperate my Business Logic into a seperate project and define services which wrap my repositories so that I can return POCOs instead of the NHibernate proxies and maintain more seperation between my Front end and DA logic. This will also give me the power to easily provide the same logic as an API later (a requirement).</p>
  
  <p>I have chosen to use a generic <code>IRepository&lt;T&gt;</code> interface where <code>T</code> is one of my NHibernate mapped Entities which all implement IEntity (my interface only a marker really).</p>
  
  <p>The problem is this goes against the aggregate root pattern and I'm starting to feel the pain of the anemic domain model.</p>
  
  <p>If I change an object that is hanging of another</p>
  
  <ul>
  <li>Root &lt;- changed
  
  <ul>
  <li>Child &lt;- changed</li>
  </ul></li>
  </ul>
  
  <p>In my service I have to do the following:</p>
  
  <pre><code>public void AddNewChild(ChildDto child, rootId)
  {
      var childEntity = Mapper.Map&lt;ChildDto,ChildEntity&gt;(child);
      var rootEntity = _rootrepository.FindById(rootId);
      rootEntity.Children.Add(childEntity);
      _childRepository.SaveOrUpdate(child);
      _rootRepository.SaveOrUpdate(root);
  }
  </code></pre>
  
  <p>If I don't save the child first I get an exception from NHibernate. I feel like my generic repository (I currently require 5 of them in one service) is not the right way to go.</p>
  
  <pre><code> public Service(IRepository&lt;ThingEntity&gt; thingRepo, IRepository&lt;RootEntity&gt; rootRepo, IRepository&lt;ChildEntity&gt; childRepo, IRepository&lt;CategoryEntity&gt; catRepo, IRepository&lt;ProductEntity&gt; productRepo)
  </code></pre>
  
  <p>I feel like instead of making my code more flexible, it's making it more brittle. If I add a new table I need to go and change the constructor in all my tests (I'm using DI for the implementation so that's not too bad) but it seems a bit smelly.</p>
  
  <p>Does anyone have any advice on how to restructure this sort of architecture?</p>
  
  <p>Should I be making my repositories more specific? Is the service abstraction layer a step too far?</p>
  
  <p><strong>EDIT</strong>: There's some great related questions which are helping:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/1347687/repository-pattern-best-practice">Repository Pattern Best Practice</a></li>
  <li><a href="https://stackoverflow.com/questions/4471630/repository-pattern-help">repository pattern help</a></li>
  <li><a href="https://stackoverflow.com/questions/2461857/architectural-conundrum">Architectural conundrum</a></li>
  </ul>