Service locator is not an anti pattern

I'm getting really tired of all blog posts that states that service locator is an anti pattern. It's not.

(this article have been rewritten since it didn't seem like I managed to communicate my thoughts properly).

There are several blog posts that states that service locator is an anti pattern. With this article I'll try to explain why it's not. Do understand that I'm not saying that it should be used for dependency management.

Let's start by examining where the pattern doesn't fit (which most blog entries uses as a "proof" for when it's an anti pattern).

Here are two quotes from different blogs:

In short, the problem with Service Locator is that it hides a class’ dependencies, causing run-time errors instead of compile-time errors, as well as making the code more difficult to maintain because it becomes unclear when you would be introducing a breaking change.

Another blog:

The problem with a Service Locator is that it hides dependencies in your code making them difficult to figure out and potentially leads to errors that only manifest themselves at runtime. If you use a Service Locator your code may compile but hide the fact that the Service Locator has been incorrectly configured. At runtime, when your code makes use of the Service Locator to resolve a dependency that hasn’t been configured, an error will occur. The compiler wasn’t able to help. Moreover, by using a Service Locator you can’t see from the API exactly what dependencies a given class may have.

So what they are saying is that the pattern can hide dependencies and force you to run your application to discover it. I fully agree. It can do that.

I agree 100%. The service locator do not work very well in that case. I strongly discourage you from abusing the locator in that way. Dependencies/information which is required should always be injected through the constructor.

Is it an anti-pattern?

We have identified use cases where the pattern doesn't fit. Does that make it an anti pattern? Of course not. Let's examine when it's perfectly valid.

Let's start with the very definition of service locator (from wikipedia):

The service locator pattern is a design pattern used in software development to encapsulate the processes involved in obtaining a service with a strong abstraction layer. This pattern uses a central registry known as the "service locator" which on request returns the information necessary to perform a certain task.

What it's saying is that the service locator basically is something that abstracts away the mapping between the requested type and implementations of something. That is that when requesting a service we do not have to care about the actual implementation.

Doesn't that sound awfully a lot like a inversion of control container? It does. Because an IoC container is nothing more than a service locator with lifetime management when all registrations have been configured.

Let's start by taking an example from the SimpleInjector documentation:

He do warn about using the container as service locator. But the point is that every container can be used as a service locator. Why is that? Because it's the easiest way to allow others to take advantage of all services that the container manages.

So when you are using any framework that have IoC support (like ASP.NET MVC) you can safely assume that they use the service location features of your favorite container.

Summary

My point is that you can abuse any pattern, but that doesn't make it an anti pattern. The reason to why Singleton and Service Locator got such a bad reputation is that they are easy to understand, implement and use. The problem is that the implementors/users haven't fully understood the problem that the patterns are trying to solve.

Here is a challenge for all of you that claims that it's an anti pattern:

Pretend that you are developer at Microsoft working with ASP.NET MVC. You want to let your framework users inject dependencies into the Controllers. But since you've read that service location is an anti pattern you'll want to replace it with something else (which supports scoping).

Anyone of you that can present a solution which is cleaner than my defined interfaces above will get my eternal respect.

Comments and Discussions

There is a difference between SL and IoCC, and it's about who drives the dependencies.
I think it's important to state up-front that both systems are workable. What matters is the level of risk and transparency you get with each model.

If I, as a consumer of that class, want to know how to construct it, it's not at all obvious (without inspecting the code, in some detail) that it will (at some stage, possibly well into its lifespan) require an implementation of ISomeRepository.

So if I'm a dumb user of your library, I'll need to read the documentation and study the code to know that I'll need to register an implementation of ISomeRepository with the ServiceLocator in order for the code to work. I'll then have to test the (insert expletive here) out of the code to be sure that it's going to work, and that the documentation didn't omit any other interfaces I might need. Or call off to another piece of code that, itself, asks for new and interesting interfaces from the ServiceLocator that I forgot to register.

Look at the IoC version of the code, and the constructor will take an ISomeRepository parameter. I cannot construct the object without all of its required dependencies - the compiler sees to that. I'm back to compile-time error checking, and very much happier.

Testing is another area where the constructor-injection approach wins out over the ServiceLocator pattern.
It's much easier for a test to have total control over the construction of all dependencies through constructor-injection rather than at arms-length through the ServiceLocator. To say nothing of what happens if the ServiceLocator pattern is itself implemented as a Singleton.

As far as your article goes, it seems to argue against ServiceLocator, but with one specific use-case where you can't see how to solve it without the SL pattern - i.e. a generic subscription pattern in which you're using the SL to identify the listeners.
I'm not sure I see a real-world use-case for this, or whether associating listeners via IoC is a good idea, so it's difficult to discuss, but this use-case in itself is no justification to go off using the SL pattern elsewhere.
If you want an example of the generic subscription pattern implemented using IoC (i.e not SL), then seeEvent Driven Architecture: Publishing Events using an IOC container[^]

If I, as a consumer of that class, want to know how to construct it, it's not at all obvious (without inspecting the code, in some detail) that it will (at some stage, possibly well into its lifespan) require an implementation of ISomeRepository

That's exactly my point. You should not use SL in your business logic.

John Brett wrote:

So if I'm a dumb user of your library, I'll need to read the documentation and study the code to know that I'll need to register an implementation of ISomeRepository with the ServiceLocator in order for the code to work

No. The documentation would state that you need to create an adapter between my library and your service locator (which every inversion of control container is).

John Brett wrote:

Look at the IoC version of the code, and the constructor will take an ISomeRepository parameter. I cannot construct the object without all of its required dependencies - the compiler sees to that. I'm back to compile-time error checking, and very much happier.

We fully agree.

John Brett wrote:

As far as your challenge goes, Mark has already written several articles on IoC within ASP.Net., which would be well worth reviewing.

As far as your article goes, it seems to argue against ServiceLocator, but with one specific use-case where you can't see how to solve it without the SL pattern - i.e. a generic subscription pattern in which you're using the SL to identify the listeners.

Yes. It argue against SL for business logic. The purpose of the whole article was to demonstrate that the pattern do have it's uses and that most people got the pattern wrong.

It's a perfect pattern when it comes to define an adapter between libraries and IoC containers.

OK, so I'm going to state that I don't think your article is very clear at explaining itself.

If you're happy to say SL isn't suitable for business logic, I can't see your argument that everything is suddenly different and invalidates all the previous arguments as soon as you start writing libraries.

I would like to suggest that you step back and have another go at clearly articulating the use-case you obviously have which requires an SL over an IoCC.
Preferably without descending into requiring static classes and singletons, but that's just my preference.