150
votes

Recently I've read Mark Seemann's article about Service Locator anti-pattern.

Author points out two main reasons why ServiceLocator is an anti-pattern:

  1. API usage issue (which I'm perfectly fine with)
    When class employs a Service locator it is very hard to see its dependencies as, in most cases, class has only one PARAMETERLESS constructor. In contrast with ServiceLocator, DI approach explicitly exposes dependencies via constructor's parameters so dependencies are easily seen in IntelliSense.

  2. Maintenance issue (which puzzles me)
    Consider the following expample

We have a class 'MyType' which employs a Service locator approach:

public class MyType
{
    public void MyMethod()
    {
        var dep1 = Locator.Resolve<IDep1>();
        dep1.DoSomething();
    }
}

Now we want to add another dependency to class 'MyType'

public class MyType
{
    public void MyMethod()
    {
        var dep1 = Locator.Resolve<IDep1>();
        dep1.DoSomething();
            
        // new dependency
        var dep2 = Locator.Resolve<IDep2>();
        dep2.DoSomething();
    }
}

And here is where my misunderstanding starts. The author says:

It becomes a lot harder to tell whether you are introducing a breaking change or not. You need to understand the entire application in which the Service Locator is being used, and the compiler is not going to help you.

But wait a second, if we were using DI approach, we would introduce a dependency with another parameter in constructor (in case of constructor injection). And the problem will be still there. If we may forget to setup ServiceLocator, then we may forget to add a new mapping in our IoC container and DI approach would have the same run-time problem.

Also, author mentioned about unit test difficulties. But, won't we have issues with DI approach? Won't we need to update all tests which were instantiating that class? We will update them to pass a new mocked dependency just to make our test compilable. And I don't see any benefits from that update and time spending.

I'm not trying to defend Service Locator approach. But this misunderstanding makes me think that I'm losing something very important. Could somebody dispel my doubts?

UPDATE (SUMMARY):

The answer for my question "Is Service Locator an anti-pattern" really depends upon the circumstances. And I definitely wouldn't suggest to cross it out from your tool list. It might become very handy when you start dealing with legacy code. If you're lucky enough to be at the very beginning of your project then the DI approach might be a better choice as it has some advantages over Service Locator.

And here are main differences which convinced me to not use Service Locator for my new projects:

  • Most obvious and important: Service Locator hides class dependencies
  • If you are utilizing some IoC container it will likely scan all constructor at startup to validate all dependencies and give you immediate feedback on missing mappings (or wrong configuration); this is not possible if you're using your IoC container as Service Locator

For details read excellent answers which are given below.

8
"Won't we need to update all tests which were instantiating that class?" Not necessarily true if you are using a builder in your tests. In this case you would only have to update the builder.Peter Karlsson
You're right, it depends. In large Android apps, for example, so far people have been very reluctant to use DI because of performance concerns on low spec mobile devices. In such cases, you have to find an alternative to still write testable code, and I'd say Service Locator is a good-enough substitute in that case. (Note: things may change for Android when the new Dagger 2.0 DI framework is mature enough.)G. Lombard
Note that since this question has been posted, there is an update on Mark Seemann's Service Locator is an Anti-Pattern post describing how service locator violates OOP by breaking encapsulation, which is his best argument yet (and the underlying reason for all of the symptoms that he used in all prior arguments). Update 2015-10-26: The fundamental problem with Service Locator is that it violates encapsulation.NightOwl888
Here is an excerpt from DIPP&P that summarizes Service Locator and its main problem.Steven

8 Answers

135
votes

If you define patterns as anti-patterns just because there are some situations where it does not fit, then YES it's an anti pattern. But with that reasoning all patterns would also be anti patterns.

Instead we have to look if there are valid usages of the patterns, and for Service Locator there are several use cases. But let's start by looking at the examples that you have given.

public class MyType
{
    public void MyMethod()
    {
        var dep1 = Locator.Resolve<IDep1>();
        dep1.DoSomething();

        // new dependency
        var dep2 = Locator.Resolve<IDep2>();
        dep2.DoSomething();
    }
}

The maintenance nightmare with that class is that the dependencies are hidden. If you create and use that class:

var myType = new MyType();
myType.MyMethod();

You do not understand that it has dependencies if they are hidden using service location. Now, if we instead use dependency injection:

public class MyType
{
    public MyType(IDep1 dep1, IDep2 dep2)
    {
    }

    public void MyMethod()
    {
        dep1.DoSomething();

        // new dependency
        dep2.DoSomething();
    }
}

You can directly spot the dependencies and cannot use the classes before satisfying them.

In a typical line of business application you should avoid the use of service location for that very reason. It should be the pattern to use when there are no other options.

Is the pattern an anti-pattern?

No.

For instance, inversion of control containers would not work without service location. It's how they resolve the services internally.

But a much better example is ASP.NET MVC and WebApi. What do you think makes the dependency injection possible in the controllers? That's right -- service location.

Your questions

But wait a second, if we were using DI approach, we would introduce a dependency with another parameter in constructor (in case of constructor injection). And the problem will be still there.

There are two more serious problems:

  1. With service location you are also adding another dependency: The service locator.
  2. How do you tell which lifetime the dependencies should have, and how/when they should get cleaned up?

With constructor injection using a container you get that for free.

If we may forget to setup ServiceLocator, then we may forget to add a new mapping in our IoC container and DI approach would have the same run-time problem.

That's true. But with constructor injection you do not have to scan the entire class to figure out which dependencies are missing.

And some better containers also validate all dependencies at startup (by scanning all constructors). So with those containers you get the runtime error directly, and not at some later temporal point.

Also, author mentioned about unit test difficulties. But, won't we have issues with DI approach?

No. As you do not have a dependency to a static service locator. Have you tried to get parallel tests working with static dependencies? It's not fun.

40
votes

I would also like to point out that IF you are refactoring legacy code that the Service Locator pattern is not only not an anti-pattern, but it is also a practical necessity. No-one is ever going to wave a magic wand over millions of lines of code and suddenly all that code is going to be DI ready. So if you want to start introducing DI to an existing code base it is often the case that you will change things to become DI services slowly, and the code that references these services will often NOT be DI services. Hence THOSE services will need to use the Service Locator in order to get instances of those services that HAVE been converted to use DI.

So when refactoring large legacy applications to start to use DI concepts I would say that not only is Service Locator NOT an anti-pattern, but that it is the only way to gradually apply DI concepts to the code base.

9
votes

From the testing point of view, Service Locator is bad. See Misko Hevery's Google Tech Talk nice explanation with code examples http://youtu.be/RlfLCWKxHJ0 starting at minute 8:45. I liked his analogy: if you need $25, ask directly for money rather than giving your wallet from where money will be taken. He also compares Service Locator with a haystack that has the needle you need and knows how to retrieve it. Classes using Service Locator are hard to reuse because of it.

7
votes

Maintenance issue (which puzzles me)

There are 2 different reasons why using service locator is bad in this regard.

  1. In your example, you are hard-coding a static reference to the service locator into your class. This tightly couples your class directly to the service locator, which in turns means it won't function without the service locator. Furthermore, your unit tests (and anybody else who uses the class) are also implicitly dependent on the service locator. One thing that has seemed to go unnoticed here is that when using constructor injection you don't need a DI container when unit testing, which simplifies your unit tests (and developers' ability to understand them) considerably. That is the realized unit testing benefit you get from using constructor injection.
  2. As for why constructor Intellisense is important, people here seem to have missed the point entirely. A class is written once, but it may be used in several applications (that is, several DI configurations). Over time, it pays dividends if you can look at the constructor definition to understand a class's dependencies, rather than looking at the (hopefully up-to-date) documentation or, failing that, going back to the original source code (which might not be handy) to determine what a class's dependencies are. The class with the service locator is generally easier to write, but you more than pay the cost of this convenience in ongoing maintenance of the project.

Plain and simple: A class with a service locator in it is more difficult to reuse than one that accepts its dependencies through its constructor.

Consider the case where you need to use a service from LibraryA that its author decided would use ServiceLocatorA and a service from LibraryB whose author decided would use ServiceLocatorB. We have no choice other than using 2 different service locators in our project. How many dependencies need to be configured is a guessing game if we don't have good documentation, source code, or the author on speed dial. Failing these options, we might need to use a decompiler just to figure out what the dependencies are. We may need to configure 2 entirely different service locator APIs, and depending on the design, it may not be possible to simply wrap your existing DI container. It may not be possible at all to share one instance of a dependency between the two libraries. The complexity of the project could even be further compounded if the service locators don't happen to actually reside in the same libraries as the services we need - we are implicitly dragging additional library references into our project.

Now consider the same two services made with constructor injection. Add a reference to LibraryA. Add a reference to LibraryB. Provide the dependencies in your DI configuration (by analyzing what is needed via Intellisense). Done.

Mark Seemann has a StackOverflow answer that clearly illustrates this benefit in graphical form, which not only applies when using a service locator from another library, but also when using foreign defaults in services.

2
votes
1
votes

My knowledge is not good enough to judge this, but in general, I think if something has a use in a particular situation, it does not necessarily mean it cannot be an anti-pattern. Especially, when you are dealing with 3rd party libraries, you don't have full control on all aspects and you may end up using the not very best solution.

Here is a paragraph from Adaptive Code Via C#:

"Unfortunately, the service locator is sometimes an unavoidable anti-pattern. In some application types— particularly Windows Workflow Foundation— the infrastructure does not lend itself to constructor injection. In these cases, the only alternative is to use a service locator. This is better than not injecting dependencies at all. For all my vitriol against the (anti-) pattern, it is infinitely better than manually constructing dependencies. After all, it still enables those all-important extension points provided by interfaces that allow decorators, adapters, and similar benefits."

-- Hall, Gary McLean. Adaptive Code via C#: Agile coding with design patterns and SOLID principles (Developer Reference) (p. 309). Pearson Education.

0
votes

The Author reasons that "the compiler won't help you" - and it is true. When you deign a class, you will want to carefully choose its interface - among other goals to make it as independent as ... as it makes sense.

By having the client accept the reference to a service (to a dependency) through explicit interface, you

  • implicitly get checking, so the compiler "helps".
  • You're also removing the need for the client to know something about the "Locator" or similar mechanisms, so the client is actually more independent.

You're right that DI has its issues / disadvantages, but the mentioned advantages outweigh them by far ... IMO. You're right, that with DI there is a dependency introduced in the interface (constructor) - but this is hopefully the very dependency that you need and that you want to make visible and checkable.

0
votes

Service Locator(SL)

Service Locator solves [DIP + DI] issue. It allows by interface name satisfy needs

class A {
  IB ib

  init() {
     ib = ServiceLocator.resolve<IB>();
  }
}

The problem here that it is not clear which exactly classes(realizations of IB) are used by client(A). Service Locator can be as singleton or can be passed into constructor.

proposal:

class A {
  IB ib

  init(ib: IB) {
     self.ib = ib
  }
}

SL vs DI IoC Container(framework)

SL is about saving instances when DI IoC Container(framework) is more about creating instances.

SL works as a PULL command when it retrieves dependencies inside constructor DI IoC Container(framework) works as a PUSH command when it put dependencies into constructor