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

By | November 21, 2013

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.

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

  1. Josh Adell

    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.

    Reply
  2. pmjones Post author

    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.

    Reply
  3. hajo

    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.

    Reply
  4. Pingback: Quicker, Easier, More Seductive: Restraining Your Service Locators | Paul M. Jones

Leave a Reply

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