What is the actual difference betwen a service locatior and a dependency injection?

被刻印的时光 ゝ 提交于 2019-12-02 09:43:15

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!