ServiceLocator is like the Dark Side: Quicker, Easier, More Seductive

When it comes to Inversion of Control, a Service Locator is like the Dark Side of the Force: quicker, easier, more seductive. But it gets you into trouble later on. Go with Dependency Injection whenever you can instead.

A lot of things calling themselves Dependency Injection containers are actually Service Locators. If you inject the container into an object, or if you call it statically from inside an object, and the object then pulls things out of the container, the container is acting as a Service Locator.

Are you stuck with a legacy PHP application? You should buy my book because it gives you a step-by-step guide to improving your codebase, all while keeping it running the whole time.

28 thoughts on “ServiceLocator is like the Dark Side: Quicker, Easier, More Seductive

  1. Interesting that Fowler prefers Service Locator over DI in the linked article: “Inversion of control is a common feature of frameworks, but it’s something that comes at a price. It tends to be hard to understand and leads to problems when you are trying to debug. So on the whole I prefer to avoid it unless I need it. This isn’t to say it’s a bad thing, just that I think it needs to justify itself over the more straightforward alternative.”

    I tend to think DI is easier to use and debug than SL, even when not using a DI container.

  2. Hi Josh,

    “Interesting that Fowler prefers Service Locator over DI in the linked article …”

    In the quote you give, he is talking about Inversion of Control in general, not SL vs DI variations of IoC. Indeed, at the very end of his article, he mentions his overall assessment of the two approaches:

    “When building application classes the two are roughly equivalent, but I think Service Locator has a slight edge due to its more straightforward behavior. However if you are building classes to be used in multiple applications then Dependency Injection is a better choice.”

    And I agree that DI is a lot easier to deal with, *especially* without a container. But in even moderately complex apps, a DI container is very useful.

  3. Service Locator and DI can be combined while both can – when used with care – enhance IoC in a software project. I think both got pros and cons while helping to get better structured code.

    From my experience developing an SL takes way more time then a DIC, because the planning phase must be done very carefully since later changes can get complicated. When done an SL makes life alot easier in the long run compared to a DIC: Better debugging, better testing, more clean code in THAT project. Therefore i just recommend DIC for code that heavily relies on reuse by OTHER projects.

Leave a Reply

Your email address will not be published. Required fields are marked *