title: Dependency Injection - where to put my repository object
body: <p>I am currently in the process of converting a large web service to use the repository pattern and dependency injection.  We are expanding our team and the benefits of reliable unit testing outweighs the effort required to refactor the code.</p>
  
  <p>I have chosen Ninject as my framework based on the recommendation of a colleague and have begun refactoring my code.  This has involved creating a "Common" project that contains the objects themselves, a Repository.Database project to contain the data access logic, and a web service that uses both.  I have used convention based mapping so that IPersonRepository should map to my concrete PersonRepository class.</p>
  
  <p>I am currently taking the approach of creating a "Repository" property on each class with the [Inject] attribute, then replacing my constructors to use said repository, but have run into my first stumbling block and am not convinced I am doing things the right way.  Before I started all this, I would instantiate an object like so:</p>
  
  <pre><code>var p = new Person(ID);
  </code></pre>
  
  <p>And using the format I suggested, my class looks something like this:</p>
  
  <pre><code>[Inject]
  public IPersonRepository Repository { get; set; }
  
  public string Name;
  
  public Person(int ID)
  {
      // This feels wrong
      var p = Repository.Get(ID);
      Name = p.Name;
  }
  </code></pre>
  
  <p>You can probably see my conundrum.  How can I use a constructor without having to return a new object from the repository and then map each field to my current object?  I can't replace "this", and while I could use something like AutoMapper to map each field in one go, it feels like I am doing something inherently wrong here.</p>
  
  <p>I could use a static method instead of an injector:</p>
  
  <pre><code>[Inject]
  public static IPersonRepository Repository { get; set; }
  
  public string Name;
  
  public static Person GetByID(int ID)
  {
      return Repository.Get(ID);
  }
  </code></pre>
  
  <p>But as you can see it requires making Repository static, and it feels like I should be using a constructor rather than a static "GetByID" method.  That could just be because I am so used to using a constructor.</p>
  
  <p>Alternatively I can pass the Repository into the Person constructor, but again, it feels messy to do that every time I instantiate a Person in code.</p>
  
  <p>What I am trying to achieve is to have my existing WCF project load all of its data using one repository, and for my Unit Test project to load all its data using another.  I don't want to have to pass concrete implementations of IPersonRepository in either.  Is this achievable and even recommended?</p>