Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

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.

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.

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.

Licensed under: CC-BY-SA with attribution
scroll top