title: Dependency injection in unit of work pattern using repositories
body: <p>I want to create a unit of work class that wraps around repositories in a similar way to <a href="http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application" rel="noreferrer">this</a>. </p>
  
  <p>The problem I'm having is trying to implement dependency injection by replacing the generic repositories in the example with an IRepository interface. In the uow in the linked article they use getters to check if the repository is instantiated and if it isn't then instantiate it.</p>
  
  <pre><code>public GenericRepository&lt;Department&gt; DepartmentRepository
  {
      get
      {
          if (this.departmentRepository == null)
          {
              this.departmentRepository = new GenericRepository&lt;Department&gt;(context);
          }
          return departmentRepository;
      }
  }
  </code></pre>
  
  <p>Which is strongly coupled.</p>
  
  <p>I can see two ways around this.</p>
  
  <ol>
  <li>Use constructor injection.</li>
  <li>Use setter injection.</li>
  </ol>
  
  <p>The problem with 1 is that if I inject all the repositories I have to instantiate each repository even if I don't use them in that particular unit of work instance. Thus incurring the overhead of doing so. I was imagining using one, database-wide, unit of work class so this would lead to a lot of needless instantiating and a gigantic constructor.</p>
  
  <p>The problem with 2 is that it would be easy to forget to set and end up with null reference exceptions.</p>
  
  <p>Is there any sort of best practices in this scenario? And are there any other options I have missed?</p>
  
  <p>I'm just getting in to dependency injection and have done all the research I can find on the topic but I may be missing something key.</p>