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

前端 未结 2 766
深忆病人
深忆病人 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: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.

提交回复
热议问题