What is the difference between a DIC and a Service Locator?

What is the difference between a DIC (dependency injection container) and a Service Locator? I just recently learned about DICs, but have a difficult time finding information on service locators (although many articles use the term it is not spelled out). I even see some people call some DICs actually service locators, and not true DICs, but I don’t understand the difference. I don’t use a framework yet so I don’t experience there to build off of. I don’t know what a service locator is and don’t know of any good examples or articles on the idea (wikipedia is no help to me - I thought of calling my topic what is a service locator.). I’m trying to improve my knowledge of OOP best practices.

1 Like

Hi Torite,

The term Service Locator actually describes a pattern of usage. With dependency injection, you’re explicitly passing the required dependencies into an object:

class RegistrationService
{
    public function __construct(UserRepository $repository, SmtpMailer $mailer)
    {
        $this->repo = $repository;
        $this->mailer = $mailer;
    }
}

however, with service location you’re passing your service locator object into a class and allowing that class to get the services it needs:

class RegistrationService
{
    public function __construct(ServiceLocator $locator)
    {
        $this->repo = $locator->get('UserRepository');
        $this->mailer = $locator->get('SmtpMailer');
    }
}

This is often considered an anti-pattern though, as the real dependencies are hidden inside the class and not made explicit by its constructor arguments. DICs are sometimes used as service locators, which is why there’s often confusion between the two terms.

This article does a good job of explaining the topic, if you want to read further.

2 Likes

I did not find that article, amazingly. I will read it and if anything is unclear, return. Thank you!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.