Having read Mark Seemann's blog post along with this response which references it, I understand the disadvantages of using the Service Locator pattern over dependency injection via a class constructor. I also read this Dependency Injection with Ninject, MVC 3 and using the Service Locator Pattern which discusses the issue as well.
However, my question concerns this particular case:
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.
}
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.
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.
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.