title: How to get a mock repository into a model object
body: <p>I am creating some unit tests for a Country model object. This is partly-generated by the Linq-to-SQL mechanism from a database table and partly under my control. This class uses the CountryRepository for some checks when checking it is valid; particularly that a country of this name doesn't already exist in the database.</p>
  
  <p>As one ought not to embroil oneself in the database during unit tests, I created a mock repository to provide pretend data, and modify the model class like this:-</p>
  
  <pre><code>public partial class Country
  {
      private ICountryRepository country_repository;
  
      public Country(ICountryRepository passed_country_repository)
      {
          country_repository = passed_country_repository;
      }
  
      //...etc
  </code></pre>
  
  <p>I can then construct this object in the test like this:-</p>
  
  <pre><code>Country test_country = new Country(new MockCountryRepository())
                         {
                              // code in here
                         };
  </code></pre>
  
  <p>and the tests run satisfactorily.</p>
  
  <p>The problem comes in actual live usage; I have to prefix every usage of the repository with this:-</p>
  
  <pre><code>if (country_repository == null)
  {
      country_repository = new CountryRepository();
  }
  </code></pre>
  
  <p>as the <code>country_repository</code> variable is unset if the zero-parameter constructor is invoked. I originally had the declaration line reading:-</p>
  
  <pre><code>private ICountryRepository country_repository = new CountryRepository();
  </code></pre>
  
  <p>but that attempts a database connection whichever constructor is used. I can't change the zero-parameter constructor to set <code>country_repository</code> to anything because it is automatically-generated and my changes might disappear at zero notice.</p>
  
  <p>Is there a better way of getting the MockCountryRepository into the model object? Or have I missed the point here somewhere, and if so, what should I be doing?</p>