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 able to get that. Can I get a general response without any code?
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<IUserRepository>();
}
}
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<IUserRepository>();
}
}
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<IUserRepository>();
}
}
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.
If you use a service locator, it usually means that you explicitly ask some object to create another object for you, which is usually considered an anti-pattern. Dependency injection is the other way around.
Say you have a class called Warrior, which has a Weapon.
Using the service locator, you would ask the service locator for a Weapon in the constructor of the Warrior.
Using dependency injection, the Weapon would be injected into the constructor of the Warrior, without you explicitly asking for it.
来源:https://stackoverflow.com/questions/12159875/what-is-the-actual-difference-betwen-a-service-locatior-and-a-dependency-injecti