title: Where  to move constructing of disposable dependencies to improve testability?
body: <p>In my unit tests, I use things like <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.assemblyinitializeattribute.aspx" rel="nofollow"><code>AssemblyInitialize</code></a>, <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.classinitializeattribute.aspx" rel="nofollow"><code>ClassInitialize</code></a> and <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.testinitializeattribute%28v=VS.100%29.aspx" rel="nofollow">TestInitialize</a> to configure my tests. In <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.assemblyinitializeattribute.aspx" rel="nofollow"><code>AssemblyInitialize</code></a> I initialize some singleton factories for creating services, a unit of work and repositories (all trough Unity/Dependency Injection). In my <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.testinitializeattribute%28v=VS.100%29.aspx" rel="nofollow">TestInitialize</a> I clear the state they have to make sure each test can run independently.</p>
  
  <p>Trough Stackoverflow I came around the following articles: <a href="http://misko.hevery.com/code-reviewers-guide/" rel="nofollow">Writing Testable Code</a> and <a href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/" rel="nofollow">How to Think About the “new” Operator with Respect to Unit Testing</a>. I have to say they changed how I think about some code I've written but my mind is still buzzing.</p>
  
  <p>For example, take the following code:</p>
  
  <pre><code>public class MyPresenter : BasePresenter&lt;IMyView&gt;
  {
      public MyPresenter(IMyView view) 
          : base(view)
      {
      }
  
      public void PrepareView()
      {
          using (IMyService service = ServiceFactory.Instance.CreateService&lt;IMyService&gt;())
          {
              View.Data = service.GetData();
          }
      }
  }
  </code></pre>
  
  <p>Which is used in an aspx page like this:</p>
  
  <pre><code>Presenter = new MyPresenter(this);
  if (!IsPostback)
  {
      presenter.PrepareView();
  }
  </code></pre>
  
  <p>How should I change this type of kind with the previous articles in mind? Should I pass a service instance to the PrepareView method? But then my ASPX page has to know about services and factories and stuff and dispose of the service after it's used.</p>
  
  <p>What should I do with my Singleton factory? Make it a property of the class and inject it trough Unity?</p>