108

I understand that directly instantiating dependencies inside a class is considered bad practise. This makes sense as doing so tightly couples everything which in turn makes testing very hard.

Almost all the frameworks I've come across seem to favour dependency injection with a container over using service locators. Both of them seem to achieve the same thing by allowing the programmer to specify what object should be returned when a class requires a dependency.

What's the difference between the two? Why would I choose one over the other?

  • 3
    This has been asked (and answered) on StackOverflow: stackoverflow.com/questions/8900710/… – Kyralessa Apr 23 at 8:07
  • 2
    In my opinion it is not at all uncommon for developers to deceive others into thinking that their service locator is dependency injection. They do that because dependency injection is often thought to be more advanced. – Gherman Apr 23 at 11:52
  • 4
    martinfowler.com/articles/… – molnarm Apr 23 at 13:31
  • 1
    I'm surprised no-one has mentioned that with Service Locators it's harder to know when a transient resource can be destructed. I always thought that was the primary reason. – Buh Buh Apr 26 at 9:22
126

When the object itself is responsible for requesting its dependencies, as opposed to accepting them through a constructor, it's hiding some essential information. It's only mildly better than the very tightly-coupled case of using new to instantiate its dependencies. It reduces coupling because you can in fact change the dependencies it gets, but it still has a dependency it can't shake: the service locator. That becomes the thing that everything is dependent on.

A container that supplies dependencies through constructor arguments gives the most clarity. We see right up front that an object needs both an AccountRepository, and a PasswordStrengthEvaluator. When using a service locator, that information is less immediately apparent. You'd see right away a case where an object has, oh, 17 dependencies, and say to yourself, "Hmm, that seems like a lot. What's going on in there?" Calls to a service locator can be spread around the various methods, and hide behind conditional logic, and you might not realize you have created a "God class" -- one that does everything. Maybe that class could be refactored into 3 smaller classes that are more focused, and hence more testable.

Now consider testing. If an object uses a service locator to get its dependencies, your test framework will also need a service locator. In a test, you'll configure the service locator to supply the the dependencies to the object under test -- maybe a FakeAccountRepository and a VeryForgivingPasswordStrengthEvaluator, and then run the test. But that's more work than specifying dependencies in the object's constructor. And your test framework also becomes dependent on the service locator. It's another thing you have to configure in every test, which makes writing tests less attractive.

Look up "Serivce Locator is an Anti-Pattern" for Mark Seeman's article about it. If you're in the .Net world, get his book. It's very good.

  • 1
    Reading the question I thought about Adaptive Code via C# by Gary McLean Hall, which aligns pretty well with this answer. It has some good analogies like the service locator being the key to a safe; when handed to a class, it may create dependencies at will that might not be easy to spot. – Dennis Apr 23 at 6:07
  • 10
    One thing IMO needs to be added to the constructor supplied dependencies vs service locator is that the former one can be verfied compile-time, while the latter one can only be verified runtime. – andras Apr 23 at 8:10
  • 2
    In addition, a service locator does not discourage a component from having many many dependencies. If you have to add 10 parameters to your constructor you have a pretty good sense something is wrong with your code. However, if you just happen to make 10 static calls to a service locator, it may not be readily obvious that you've got some kind of issue. I've worked on a large project with a service locator and this was the biggest issue. It was just way too easy to short circuit a new path in rather than sit back, reflect, redesign and refactor. – Pace Apr 23 at 18:51
  • 1
    About testing - But that's more work than specifying dependencies in the object's constructor. I'd like to object. With a service locator you only need to specify the 3 dependencies that you actually need for your test. With a constructor-based DI you need to specify ALL 10 of them, even if 7 are unused. – Vilx- Apr 24 at 13:51
  • 4
    @Vilx- If you have multiple unused constructor parameters then it is likely your class is violating the Single Responsibility principle. – RB. Apr 25 at 13:47
79

Imagine you are a worker in a factory that makes shoes.

You are responsible for assembling the shoes and so you'll need a lot of things in order to do that.

  • Leather
  • Measuring tape
  • Glue
  • Nails
  • Hammer
  • Scissors
  • Shoe laces

And so on.

You're at work in the factory and you're ready to start. You have list of instructions on how to proceed, but you don't have any of the materials or tools yet.

A Service Locator is like a Foreman that can help you get what you need.

You ask the Service Locator every time you need something, and they go off to find it for you. The Service Locator has been told ahead of time about what you're likely to ask for and how to find it.

You'd better hope that you don't ask for something unexpected though. If the Locator hasn't been informed ahead of time about a particular tool or material, they won't be able to get it for you, and they will just shrug at you.

service locator

A Dependency Injection (DI) Container is like a big box that gets filled with everything that everyone needs at the start of the day.

As the factory starts up, the Big Boss known as the Composition Root grabs the container and hands out everything to the Line Managers.

The Line Managers now have what they need to conduct their duties for the day. They take what they have and pass what is needed to their subordinates.

This process continues, with dependencies trickling down the line of production. Eventually a container of materials and tools shows up for your Foreman.

Your Foreman now distributes exactly what you need to you and other workers, without you even asking for them.

Basically, as soon as you show up for work, everything you need is already there in a box waiting for you. You didn't need to know anything about how to get them.

dependency injection container

  • 45
    This is an excellent description of what each of those 2 things are, super good-looking diagrams too! But this does not answer the question of "Why choose one over the other"? – Matthieu M. Apr 23 at 7:49
  • 21
    "You'd better hope that you don't ask for something unexpected though. If the Locator hasn't been informed ahead of time about a particular tool or material" But that also can be true of a DI container. – Kenneth K. Apr 23 at 14:28
  • 5
    @FrankHopkins If you omit registering a interface/class with your DI container, then your code will still compile, and it will promptly fail at runtime. – Kenneth K. Apr 24 at 4:02
  • 3
    Both are equally likely to fail, depending on how they are set up. But with a DI container, you're more likely to bump into an issue sooner, when class X is constructed, rather than later, when class X actually needs that one dependency. It's arguably better, because it's easier to run into the issue, find it and solve it. I do agree with Kenneth though, that the answer suggests this issue exists for service locators only, which is definitely not the case. – GolezTrol Apr 24 at 12:59
  • 3
    Great answer, but I think it misses one other thing; that is, if you ask the foreman at any stage for an elephant, and he does know how to get one, he will get one for you no questions asked- even though you don't need it. And someone trying to debug a problem on the floor (a developer if you will) will be wondering wtf is an elephant doing here on this desk, thus making it harder for them to reason about what is actually gone wrong. Whereas with DI, you, the worker class, declare in advance every dependency you need before you even start the job thus making it easier to reason about. – Stephen Byrne Apr 24 at 14:12
10

A couple of extra points I've found when scouring the web:

  • Injecting dependencies into the constructor makes it easier to understand what a class needs. Modern IDEs will hint what arguments the constructor accepts and their types. If you use a service locator you have to read the class through before you know which dependencies are required.
  • Dependency injection seems to adhere to the "tell don't ask" principle more than service locators. By mandating that a dependency be of a specific type you "tell" which dependencies are required. It's impossible to instantiate the class without passing the required dependencies. With a service locator you "ask" for a service and if the service locator is not configured correctly you may not get what is required.
3

I'm coming late to this party but I can't resist.

What's the difference between using dependency injection with a container and using a service locator?

Sometimes none at all. What makes the difference is what knows about what.

You know you're using a service locator when the client looking for the dependency knows about the container. A client knowing how to find its dependencies, even when going through a container to get them, is the service locator pattern.

Does this mean if you want to avoid service locator you can't use a container? No. You just have to keep clients from knowing about the container. The key difference is where you use the container.

Lets say Client needs Dependency. The container has a Dependency.

class Client { 
    Client() { 
        BeanFactory beanfactory = new ClassPathXmlApplicationContext("Beans.xml");
        this.dependency = (Dependency) beanfactory.getBean("dependency");        
    }
    Dependency dependency;
}

We've just followed the service locator pattern because Client knows how to find Dependency. Sure it uses a hard coded ClassPathXmlApplicationContext but even if you inject that you still have a service locator because Client calls beanfactory.getBean().

To avoid service locator you don't have to abandon this container. You just have to move it out of Client so Client doesn't know about it.

class EntryPoint { 
    public static void main(String[] args) {
        BeanFactory beanfactory = new ClassPathXmlApplicationContext("Beans.xml");
        Client client = (Client) beanfactory.getBean("client");

        client.start();
    }
}

<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="dependency" class="Dependency">
    </bean>

    <bean id="client" class="Client">
        <constructor-arg value="dependency" />        
    </bean>
</beans>

Notice how Client now has no idea the container exists:

class Client { 
    Client(Dependency dependency) { 

        this.dependency = dependency;        
    }
    Dependency dependency;
}

Move the container out of all clients and stick it in main where it can build an object graph of all your long lived objects. Pick one of those objects to extract and call a method on it and you start the whole graph ticking.

That moves all the static construction into the containers XML yet keeps all your clients blissfully ignorant of how to find their dependencies.

But main still knows how to locate dependencies! Yes it does. But by not spreading that knowledge around you've avoided the core problem of the service locator. The decision to use a container is now made in one place and could be changed without rewriting hundreds of clients.

1

I think that the easiest way to understand the difference between the two and why a DI container is so much better than a service locator is to think about why we do dependency inversion in the first place.

We do dependency inversion so that each class explicitly states exactly what it is dependent on for operation. We do so because this creates the loosest coupling we can achieve. The looser the coupling, the easier something is to test and refactor (and generally requires the least refactoring in the future because the code is cleaner).

Let's look at the following class:

public class MySpecialStringWriter
{
  private readonly IOutputProvider outputProvider;
  public MySpecialFormatter(IOutputProvider outputProvider)
  {
    this.outputProvider = outputProvider;
  }

  public void OutputString(string source)
  {
    this.outputProvider.Output("This is the string that was passed: " + source);
  }
}

In this class, we are explicitly stating that we need an IOutputProvider and nothing else to make this class work. This is fully testable and has a dependency upon a single interface. I can move this class to anywhere in my application, including a different project and all it needs is access to the IOutputProvider interface. If other developers want to add something new to this class, which requires a second dependency, they have to be explicit about what it is they need in the constructor.

Take a look at the same class with a service locator:

public class MySpecialStringWriter
{
  private readonly ServiceLocator serviceLocator;
  public MySpecialFormatter(ServiceLocator serviceLocator)
  {
    this.serviceLocator = serviceLocator;
  }

  public void OutputString(string source)
  {
    this.serviceLocator.OutputProvider.Output("This is the string that was passed: " + source);
  }
}

Now I've added the service locator as the dependency. Here are the problems that are immediately obvious:

  • The very first problem with this is that it takes more code to achieve the same outcome. More code is bad. It's not much more code but it is still more.
  • The second problem is that my dependency is no longer explicit. I still need to inject something into the class. Except now the thing that I want is not explicit. It's hidden in a property of the thing that I requested. Now I need access to both the ServiceLocator and the IOutputProvider if I want to move the class to a different assembly.
  • The third problem is that an additional dependency can be taken by another developer who doesn't even realise they're taking it when they add code to the class.
  • Finally, this code is harder to test (even if ServiceLocator is an interface) because we have to mock ServiceLocator and IOutputProvider instead of just IOutputProvider

So why don't we make the service locator a static class? Let's take a look:

public class MySpecialStringWriter
{
  public void OutputString(string source)
  {
    ServiceLocator.OutputProvider.Output("This is the string that was passed: " + source);
  }
}

This is much simpler, right?

Wrong.

Let's say that IOutputProvider is implemented by a very long running web service that writes the string in fifteen different databases around the world and takes a very long time to complete.

Let's try to test this class. We need a different implementation of IOutputProvider for the test. How do we write the test?

Well to do that we need to do some fancy configuration in the static ServiceLocator class to use a different implementation of IOutputProvider when it is being called by the test. Even writing that sentence was painful. Implementing it would be torturous and it would be a maintenance nightmare. We should never need to modify a class specifically for testing, especially if that class is not the class we are actually trying to test.

So now you're left with either a) a test that is causing obtrusive code changes in the unrelated ServiceLocator class; or b) no test at all. And you're left with a less flexible solution as well.

So the service locator class has to be injected into the constructor. Which means that we're left with the specific problems mentioned earlier. The service locator requires more code, tells other developers that it needs things that it doesn't, encourages other developers write worse code and gives us less flexibility moving forwards.

Put simply service locators increase coupling in an application and encourage other developers to write highly coupled code.

  • Service Locators (SL) and Dependency Injection (DI) both solve the same issue in similar manners. The only difference if if your are "telling" DI or "asking" SL for dependencies. – Matthew Whited Apr 25 at 15:26
  • @MatthewWhited The main difference is the number of implicit dependencies you take with a service locator. And that makes a massive difference to the long term maintainability and stability of the code. – Stephen Apr 28 at 23:50
  • It's really not. You have the same number of dependencies either way. – Matthew Whited Apr 29 at 14:36
  • Initially yes, but you can take dependencies with a service locator without realising you are taking dependencies. Which defeats a large part of the reason why we do dependency inversion in the first place. One class depends on properties A and B, another depends on B and C. Suddenly the Service Locator becomes a god class. The DI container doesn't and the two classes are properly only dependent on A and B and B and C respectively. This makes refactoring them a hundred times easier. Service Locators are insidious in that they appear the same as DI but they're not. – Stephen Apr 30 at 0:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.