Announcement Announcement Module
No announcement yet.
Do you need to use service locator, or can you resolve all deps with DI? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Do you need to use service locator, or can you resolve all deps with DI?

    I've recently been involved in some discussions about whether or not to use Service Locator pattern in our implementations, or go with a complete DI approach. There are some recommendations that we need to use service locator when connecting different service components to each other.

    I had claimed that
    1. Service Locator and Dependency Injection are 2 different strategies to accomplish the same goal, namely of resolving dependencies without embedding their implementation details into their consumers.
    2. You don't need to use Service Locator and Dependency Injection together
    3. It seems strange to mix strategies, especially given my opinion (recognition of reality?) that DI doesn't risk the indirect coupling that can happen between objects because of Serv. Locator, not to mention the slightly elevated test burden
    4. Many non-Spring frameworks are moving away from service locator and toward DI (JEE, SCA, OSGi), which sort of lends recognition to the idea that it may be more useful/well-suited

    Is there some obvious drawback to not using Service Locator that I'm missing?

  • #2
    Everything you are stating is fair, and in most cases DI is all you need to have a clean and flexible solution. Since you are not listing the arguments of your opponents I can't guess whether or not SL may be needed in your case. Keep in mind that sometimes the actual implementation of the module to be used in a particular scenario is not known until run-time. In such cases, you'd normally inject a factory - instead of a specific module implementation, and have the implementation instance resolved (looked up) on the fly at run-time. For example, you may have multiple implementations of parsers for different types of document formats. Depending on the format of the given document your system would have to pick the correct parser. So, you'd have to use some kind of factory look-up mechanism vs. pure injection of a specific parser implementation. HTH.