title: Service Locator Alternative in ASP.NET MVC
body: <p>Having read <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx" rel="nofollow noreferrer">Mark Seemann's blog post</a> along with <a href="https://stackoverflow.com/a/6051072/1068266">this response</a> which references it, I understand the disadvantages of using the <em>Service Locator</em> pattern over dependency injection via a class constructor. I also read this <a href="https://stackoverflow.com/questions/4607425/dependency-injection-with-ninject-mvc-3-and-using-the-service-locator-pattern">Dependency Injection with Ninject, MVC 3 and using the Service Locator Pattern</a> which discusses the issue as well.</p>
  
  <p>However, my question concerns this particular case:</p>
  
  <pre><code>public class MyController
  {
      public void GetData()
      {
          using (var repository = new Repository())
          {
              // Use the repository which disposes of an Entity Framework
              // data context at the end of its life.
          }
      }
  
      // Lots of other methods.
  }
  </code></pre>
  
  <p>Here I have a controller which contains a method that calls a repository which automatically instantiates an internal Entity Framework data context. This single data context is used, because the context is called by every method in the repository so it seems to make sense to share a single context for the entire lifetime of the repository object.</p>
  
  <p>Now, as the controller class is large, there is a greater chance than not that this given repository will not be used. As I assume (perhaps incorrectly) that this instantiating a DC is an expensive operation, I would prefer to avoid doing so. Using the service locator pattern allows me to defer instantiation until the context is actually needed, but given the valid arguments against it in the above links, I would prefer to avoid it.</p>
  
  <p>So what I would like to know is if there is a more efficient way of using dependency injection in the above case that would prevent me from instantiating my repository and underlying data context unnecessarily.</p>