I was going through the previous discussion in which there was a detailed discussion on the difference between a service locator and a dependency injector, but still I am not ab
This code sample applies the Dependency Injection principle:
public class UserService : IUserService
{
private IUserRepository repository;
// Constructor taking dependencies
public UserService(IUserRepository repository)
{
this.repository = repository;
}
}
This code sample uses the Service Locator pattern:
public class UserService : IUserService
{
private IUserRepository repository;
public UserService()
{
this.repository = ObjectFactory.GetInstance();
}
}
And this is an implementation of the Service Locator pattern:
public class UserService : IUserService
{
private IUserRepository repository;
public UserService(Container container)
{
this.repository = container.GetInstance();
}
}
And even this is an implementation of the Service Locator pattern:
public class UserService : IUserService
{
private IUserRepository repository;
public UserService(IServiceLocator locator)
{
this.repository = locator.GetInstance();
}
}
The difference is that with Dependency Injection, you inject all dependencies a consumer needs, into the consumer (but nothing else). The ideal way of injecting it is through the constructor.
With Service Locator you request the dependencies from some shared source. In the first example this was the static ObjectFactory
class, while in the second example this was the Container
instance that was injected into the constructor. The last code snippet is still an implementation of the Service Locator pattern, although the container itself is injected using dependency injection.
There are important reasons why you should use Dependency Injection over Service Locator. This article does a good job explaining it.