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

前端 未结 2 735
深忆病人
深忆病人 2021-01-26 12:53

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

相关标签:
2条回答
  • 2021-01-26 13:23

    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.

    0 讨论(0)
  • 2021-01-26 13:37

    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.

    0 讨论(0)
提交回复
热议问题