Service locator is not an anti pattern.

(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.

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.

Here is the most common example to illustrate that:

public class SomeService
	public void DoSomething()

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. So a better solution would be:

public class SomeService
	ISomeRepository _repos;
	public SomeService(ISomeRepository repos);
		if (repos == null) throw new ArgumentNullException("repos");
		_repos = repos;
	public void DoSomething()

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 contol 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:

public partial class User : BasePage
    private readonly IUserRepository repository;
    private readonly ILogger logger;

    public User()
        // 5. Retrieve instances from the container (resolve)
        this.repository = Global.Container.GetInstance<IUserRepository>();
        this.logger = Global.Container.GetInstance<ILogger>();

    protected void Page_Load(object sender, EventArgs e)
        // Use repository and logger here.

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.

A specific example

Someone suggested that the factory pattern could be used as an alternative. The problem with the factory patterns are that they should always return a new instance of an object each time they are invoked. If you do not do that you do not implement the factory pattern correctly.

ASP.NET MVC has something called action filters which allows you to invoke code at certain points in the execution pipeline. It can for instance be to commit a transaction once an action method have been executed or to authorize the user before an action have been executed.

Let’s assume that we create a factory for the controllers and one for action filters. And per definition they create a new filter or controller upon each invocation. That is not a problem since a new one should be created open each invocation. However, if the action filter should be able to commit the transaction it has to be able to access the same transaction instance that is used in the controller services (like a user repository). That is not possible if our factories just create new instances.

To get around that problem we have to start to manage transactions using solutions like [ThreadStatic] or the HttpContext. Thus introducing more complexity to the application compared to using service location.

However, the factory methods could be able to generate controllers and filters that use the same instance of the transaction. And they could do that by using the service locator in ASP.NET MVC (i.e. DependencyResolver). It’s still service location, but it’s hidden as an implementation detail in the library.


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.

  • ben

    After 10 years of using it I’m beginning to think IOC / DI is an Anti Pattern ….so the fact that a service Locator is also one doesn’t surprise me .

    The fact is an IOC container ( and a service locator ) expose a significant amount of code to anyone that has access to it . Mark Miller wrote a very good paper a number of years ago how classes should be regarded as capabilities and should obey POLA .

    Yes you can use constuctor injection but this just limits its badness and introduces worse issues like rarely used but expensive objects. This means you need to be aware how expensive an object is to create and how much its used to determine whether to use DI … which is not a good thing .. And then what do you do ? Call the Container in the methods that use it ? Lazy load it ( Which may be an issue if it uses a lot of memory and is not disposed) . Obviously the best thing is to pass it in from the caller .. but if that is valid why inject from the constructor ? Is it just because we have a proliferation of infra structure objects / factories which dont really belong on methods ( or we like to see on methods .. ) ?

    In addition there is the well established issue of not knowing what code will run and how the app is wired up, so you loose the quick learning curve and parsing of code to get to where you want.

    I think the proliferation of IOC is just because as developers we are too lazy in working out how to structure our apps so classes only have the minimum access needed. This is not much better than global statics. Maybe OO is just wrong and we should use SOA style coupling ..

    .Anyway im lost…

    Anyway if we persist with DI we should use small scopes for the container .

    maybe constructors should look like this Constructor ( subContainer , IMyCommonType)




    • I do agree with everything you say. However, I don’t blaim the container but a) the lazy developers b) container implementors that add too many features. A container applies to SRP too.

      I’ve also seen the pattern with users that think it’s OK to create a really big application just because they can do it in a loosely coupled fashion with the help of the container. It is, just as you say, better to create smaller applications using SOA or messaging. However, I would probably still use the container in them.

      As for the lifetime I always try to keep it short. When I use commands each lifetime spans over a command only. In windows services the lifetime is only when a new job is executed. In MVC it’s during the request. In winforms it’s over the command execution again.

      I do love to use an container, but it’s no magic bullet.

      • Scott

        “I don’t blaim the container but a) the lazy developers b) container implementors that add too many features.”
        I completely agree with this statement, especially the first part.
        Truth is, there is way too much hype around service locator being an anti-pattern and dependency injection frameworks (or other forms of dependency inversion) being a silver-bullet. It boils down to the fact that the human species likes to “take sides”, to become far too attached to one thing over another, to create camps of like-minded individuals with little tolerance for questioning the mental status quo (la cage aux folles).
        Software engineering, though creative, is fundamentally a science. So what of the scientific method? It requires objective observation of functional and non-functional requirements (never mind quantum mechanics for the moment). Then, after significant analysis, one should select the technologies (patterns, frameworks, platforms, etc) based on those requirements and not because “I like this pattern because it worked in my last project” or “I like this pattern because someone told me it the right one to use”, or any other not-yet-proven or bigoted view not based on actual fact. These are called knowledge claims in epistemology. They are claims not yet validated. To clarify, by “fact”, I mean that which can be reproduced time and time again yielding the same outcome. Software technology is far too contextual! Not to mention it is always evolving.
        Bottom-line: IT individuals who state that any technology is a silver bullet are doomed to a limited existence and limited, even flawed outcomes. Call it laziness, or some other form of “ignore”-ance. It boils down to people becoming far too attached to a technology – as though it were their lover – which is kinda neurotic.
        I always say: “Consider everything in its context, including what I just said.” After all, are we not developing software for the purposes of doing business (directly or indirectly)…therefore…select the technologies that best match the requirements? (Rhetorical and IMHO)

    • Just don’t conflate the Dependency Inversion Principal with IOC Containers. You don’t need a container at all to properly adhere to the DIP.

      • crushcrush

        I see this far too often. People think IoC is DI. In fact, IoC uses DI to achieve its purpose.

  • Cygon

    I can’t follow your argumentation there.
    To me, the second example demonstrates even worse design that the first. It not only is a first class example of what makes service locator an anti-pattern (the User class is going shopping for services and without reading the code/docs, one wouldn’t have a clue which other services it accesses), it also combines it with global variables. A true dependency nightmare.
    – If you want to unit test that, you’d have to push your mocks into this ‘Global.Container’. That prevents multiple tests from running in parallel right there because only one mock can be active at the same time.
    – If you add an additional service dependency to your class, it will only blow up at runtime (or possibly even create a non-mocked instance of the service in unit tests)
    – You need to run binding setup code before your unit tests can run. Thus, in the strictest sense, you aren’t even able to unit test one class in isolation and you’re actually doing integration tests.
    – Your class now depends on one specific IoC implementation. Whereas with constructor-injected dependencies the class could be used without any IoC container.
    All possible uses of a service locator class promote the kind of bad design the two examples in your post show, that’s what makes it an anti-pattern.
    The replacement in ASP.NET MVC is straightforward constructor injection. Any ASP.NET MVC bridge for popular IoC containers offers constructor-injected controller factories. Scoping (singleton, thread, call, session) is easily configured through the bindings, unless you’re referring to something else.

    • Ehh. I don’t follow your comment at all? The example shown was to demonstrate where the pattern do not fit.
      ASP.NET MVC uses service location internally to allow devs to use constructor injection and that was my point. Without service location it would be impossible to do that.

      • crushcrush

        Not impossible. Maybe more verbose and explicit – that’s the whole argument against ServiceLocator, though. ServiceLocator is not explicit. It hides complexity.

        • It’s easy to say. Show me a less complex alternative. Regarding complexity. There are several patterns that do that. It’s in their purpose. For instance the Facade pattern and the Builder pattern. That doesn’t make them anti-patterns. Hiding complexity is not necessarily a bad thing if it makes the rest of the code easier to follow and maintain. Same thing goes for frameworks. Their entire purpose is to hide complexity.

  • C. Shea

    Your example of the use of Service Locator as not being an anti-pattern is exactly what Mark Seemann talks about in his book DI in .Net in terms of it being an anti-pattern. You are hiding the fact (from the compiler) that in order to use a User object, you need to have an instance of a IUserRepository and an ILogger. When instantiating a User from a third party component, the third party potentially has no idea that User requires an IUserRepository and an ILogger implementation. If you had used straight up DI and Constructer Injection, the third party would immediately know that User has a dependency on those interfaces and knows they must be provided (either statically or resolved through some container). Also, by using Service Locator, you are now spreading out calls to instantiate dependencies for the system across your system. There is no coherent view of what your system depends on. Also, there’s a chance that when you call the Service Locator to instantiate a dependency, that the locator has not been configured (yet) with that dependency, also causing brittleness. Also, it violates the Register, Resolve, Release pattern. There are no two ways about it. Service Locator is an anti-pattern. Everywhere Service Locator is used could be refactored to use DI instead, resulting in only one place where all dependencies are registered and resolved. If there’s a problem with the container, you know where to look–in the application seam, where your DI container is setup and called to resolve all dependencies needed by the application.

    • I love to see how you would solve constructor injection in controllers in a library like ASP.NET without using service location. The constructor patterns (like factory pattern) can’t help as the same instance of a service might be shared between classes. The problem is that the library code have to be able to identify and manage a set of services which are not known at compile time nor the life time of those services.

      An inversion control container used through service location is the least complex solution for that problem. All other solutions will either be more complex for the user or the library developer. I would love to see you prove me wrong.

      We also have to remember that the term ‘Anti-pattern’ was coined as a reaction to the ‘Design Patterns’ book that GOF released. It isn’t a term that are used to label patterns that people doesn’t think apply any more.

      The term ‘Anti-patterns’ is defined to “An anti-pattern (or antipattern) is a common response to a recurring problem that is usually ineffective and risks being highly counterproductive”. I don’t see how Service Location fit that description.

      • C. Shea

        Well, for one, MVC 1.0 provided the IController interface, the ControllerBase base class, and if needed, an IControllerFactory (and probably a base, concrete implementation of that) that you could inherit from and tell MVC to use in place of its default implementations of those. This is how we did dependency injection in Asp.Net MVC 1.0.

        As far as service lifetimes between controllers and controller instantiation: Most dependency injection libraries allow you to control the lifetime of an instance registered with the container. For example, Microsoft’s Unity library has ContainerControlledLifetime (a/k/a single instance shared among all classes), PerHttpRequestLifetime (a new instance is created for each controller request), TransientLifetime (a new instance is created whenever the type is requested from the container–essentially, its lifetime is not controlled, as soon as the object goes out of scope, it can be GC’d), and there’s even a PerResolveLifetime (the first time the object is requested from the container , a given web request–for eample, the type is constructed; subsequent requests for the type during the current request result in the same instance being returned by the container).

        So, as you can see, MVC 1.0 had DI in mind and built-in right out of the box. And, most dependency injection libraries (read, the most common, most used ones) allow you to control object lifetimes.

        Mark Seeman has an example of creating a base controller wired up for dependency injection and subsequently configured to be used as the base controller by Asp.Net MVC in his book I mentioned in my original comment.

        Service Location is an anti-pattern because it hides the dependencies inside the service locator that is passed around to all of your classes. Typically, you’d have:

        Public class MyObject
        . public MyObject(ServiceLocator locator)
        . {
        . ServiceLocator myLocator = locator;
        . IMyDependency dep = locator.Resolve();
        . }

        If someone didn’t know any better (for example, someone consuming a library you developed using service location), they could just ‘new MyObject()’ with any old service locator not containing the required dependencies, and bam!, NullReferenceException–possibly many times, until all objects needed to be doled out by the locator are provided.

        Contrast this with dependency injection: ‘public class MyObject(IMyDependency dependency) {…}’ — I couldn’t possibly instantiate this class without providing the required dependency represented by the constructor parameter. The dependencies are known, they’re apparent, and they can be provided by a dependency injection container–if you choose to use DI. It’s a win-win all around.

        Hope that helps.

        • I asked you to present an alternative to using a IoC through service location that won’t increase complexity in for instance ASP.NET MVC. I ask that again as you still have not presented a solution.

          I’m well aware of lifetimes in IoCs. I’ve written a container myself. My point was that creational patterns can’t be used as you then loose control over the life time.

          Are you saying that SL is an anti pattern just because you presented a use case where it do not fit? In that case all patterns are anti patterns.

          Your second example about when the locator is not configured properly. Temporal coupling is not just a problem with locators, it applies to IoC containers, Sockets, Database connections etc. Are you suggesting that they should not be used either?

          Do remember that “Anti-pattern” is not a label to put on patterns. Read the wikipedia article for a definition.

          Looking forward to the next reply. Always interested in others perspectives.

          • C. Shea

            So, I read this blog post a long time ago, and my original comment has little resemblance to what’s here now. After having reread the post, I think I understand what you’re trying to say. But, I wouldn’t promote Service Location for managing application dependencies. In fact, Service Locator tends to be more of a fancy name for an abstract factory. And, abstract factories can be very useful. So if that’s how you’re viewing the use of a service locator–where you don’t care about the particular implementation of a service that’s guaranteed to be available to the application–by all means, use a service locator, er, abstract factory.

          • As I said, creational patterns like abstract factory cannot be used. They are expected to return a new instance on every call. If you for instance create your own filters in ASP.NET MVC you expect the same unit of work etc to be returned when using the Dependency Resolver.

            The service locator pattern do not but any semantics on whether a new instance should be returned or not, which makes it a better choice than creational patterns (as defined in the GOF book).

            I fully agree that service locator shouldn’t be used as a common solution in business code, and I really do not think that it is. It’s a great pattern for libraries due to the simple definition and the fact that an inversion of control container can be used to implement it. Simple for the library users and simple for the library developers.

            As a library developer you do not actually now which classes are required. That’s configured by the user. Let’s take ASP.NET MVC as an example again. The controllers might request a interface in the constructor. How would you solve that? You can’t just scan all assemblies in the appdomain since they might contain multiple implementations of that interface. Also you do not know if the user expected that dependency to be transient, scoped or single instance.

            The controllers are just one of the extension points in MVC. There are several. Mark Semanns solution is to define one replacement interface per integration point instead of having a service locator interface. I ask why. What advantage would that give from the library user perspective? It would just complicate things without giving any real value. Today most containers can just implement the DependencyResolver interfaces and be done with it. The MVC users just need to download a nuget package and be done with it.

            But let’s continue down that path that Mark suggests. Let’s create a factory for controllers and a factory for action filters. Now we have to well defined extension points which is great. Let’s now assume that we want to create an action filter which commits the transaction if no exceptions have been throw and if the model state is valid.

            We then want to be able to access the same instance of the transaction as used in the controller. But since we know have to distinct factories with no relation to each other we have to access the current transaction in some other way. One solution is of course to use a ThreadStatic or to put the transaction in the HttpContext. But that will just increase the complexity compared to using a service locator. Is it really worth it? In my opinion it’s not. Let libraries use the service locator pattern to be able to access the services requested by the user. It isn’t exposed to the user but it just an implementation detail in the library.

            Service locator is a pattern that shouldn’t be used in all scenarios where services have to be resolved, just like the adapter pattern doesn’t apply in all scenarios (where proxy, bridge pattern etc also are alternatives).

            Finally the anti pattern term was coined to identify commonly used solutions to specific problems where the solution is ineffective and increases complexity. Service location is not a commonly used solution. You have a list of anti patterns here: Read them and you’ll understand what the term was coined for.

          • C. Shea

            You’re right about lifetime management and the typical abstract factory.

            I would say using the HttpContext is perfectly acceptable. That’s its purpose. It’s an ambient context and precisely the way it should be used. The alternative is to create your own ambient context and register it with your container using either the PerResolveLifetime or SingletonLifetime (both are equivalent, more or less, when we’re talking about web requests). Then you can take a dependency on the ambient context where you can store things like transaction-type classes.

            As far as assembly scanning and possibly duplicately named interfaces…there’s a solution for that (with Unity anyway, and others, I’m sure). You can use named registrations. You shouldn’t probably have many duplicately named interfaces, so these are an exception to the convention. So scan first. Unity will simply overwrite an existing container registration. (This means you don’t have to write a lot of conditional logic to accomplish scanning–though, one could argue that this behavior is poor and could lead to problems–I only know this because it did lead to problems in an application I was working on). Then, go back and re-register those “exceptional” interfaces using a named registration.

            But wait, how do you get the right registration back from the container now in some cases? Some will still just work with a little additional logic to tell the container which registration to use. Others, not so much. For those, you may want to use method injection or property injection (which are sorely underused–these types of injections aren’t needed often, but they are available and perfectly acceptable when the condition warrants). I’ve used this technique to inject into action filters, for instance (though, this is generally not a good idea–the application I was working on, however, left me little choice at the time 😐)

            And just to clarify, my main aim when using DI is to loosely couple my code. My libraries don’t need to know anything about my DI container–that’s purely an application infrastructure concern. (In the same way, my libraries should not need to know about a Service Locator in order to function.) Otherwise, I would be tightly coupling my library to a particular DI container (or service locator). And again, the key here is not mixing application-level infrastructure concerns with domain and/or business logic concerns. That’s perhaps, the most insidious problem with service location that dependency injection doesn’t burden you with.

            Finally, I’ve enjoyed this thread to date and appreciate the questions and challenges–we should always be thinking critically with the aim of writing better, SOLID code.

          • You are still talking about a container. But how would you enable constructor injection if ASP.NET could not access the container through a service location interface?

            imho using the HttpContext is not an option as it would tie the business logic to ASP.NET. (unless you abstract it away which would further increase complexity).

            So you do not want to use SL because it might not contain the registered services, but you are OK with assembly scanning that might both incorrect services, and you are also OK with named registrations which are even more fragile? Then you are also fine with property injection which introduces temporal coupling?

            Seriously, now I do not understand at all why you think that SL is an anti-pattern.

            My point is that dependency injection is not possible if the base library/framework can’t resolve services through a service location interface. It isn’t something that is exposed in business code, but it’s still there to enable dependency injection. There are other options, but a service location interface is the least complex one making it a lot easier to enable support for different IoC containers. Label the pattern as an anti-pattern is like saying that the integration is “a recurring problem that is usually ineffective and risks being highly counterproductive”.

          • C. Shea

            For the record, I don’t like assembly scanning, but since you mentioned it, I ran worth it.

            Secondly, I already demonstrated that ASP.Net MVC 1.0 had extensibility built-in from day one that supports DI. You don’t need s service locator interface to bootstrap DI.

            Since DI is an application infrastructure concern, and without using assembly scanning, container registration is explicit and intentional, yes, I’m ok with named registrations.

            Property injection is a form of DI that can be used–again, I refer you to Mark’s book. He has a great write-up on when and why you might user this–but he does suggest that other forms of DI be used first, if possible.

            I was not suggesting paying around the HttpContext, as you would be right, I’d be tightly coupling my libraries to I was suggesting using the ambient context as application storage, to retrieve things out of and pad asking. While this can be done, it’s probably not the best design, and so I went further and suggested using your own ambient context resisted with the DI container proper.

            Since its apparent that you refuse to acknowledge the built-in extensibility points of MVC as far back as v1.0 that can expressly be used for the purposes of enabling DI, I guess we’ll have to agree to disagree.

          • C. Shea

            Oh, and when you’re talking about frameworks versus applications (which are two completely different things), then this conversation changes. A framework has much different design considerations than an application, and serves a completely different purpose, and may require mechanisms like service location. But, like you said, the definition of anti-pattern is such that it’s meant to be used towards those things solving a comin problem that are ineffective our problematic. People aren’t creating frameworks left and right (or at least they shouldn’t be–in the fullest sense of the messaging meaning of framework; I’m thinking BCL here). Must people are writing applications–and generally speaking, DI is a much better solution for resolving application dependencies.

          • Of course. There is a big difference between using SL in application code and in libraries/frameworks. But labeling something as an anti-pattern is saying that there are no use cases for it. SL isn’t an anti-pattern, it has it’s specific use cases. Just because you should always try to use dependency injection over SL in application code doesn’t mean that it’s an anti pattern.

            Just like I said in my blog post: A pattern isn’t an anti pattern just because it has some use cases where it doesn’t fit.

          • HB

            Brilliant discussion. But I’m siding with jgauffin. Any claim that something is “always bad” or “always good” needs to be inspected. Service Locator falls squarely into this territory. It’s like using scissors. Cutting paper for an art project… good. Cutting your mother’s curtains… bad.

          • crushcrush

            It seems that the argument here is more that it’s sometimes necessary because of the box within which we live (.NET MVC Framework). That doesn’t make it good. We simply have no other mechanism because of the design choices made by the MVC team. None of these arguments negate the key points Mark Seemann makes. Service Locator hides complexity – ALWAYS.

          • The entire purpose of MVC and similar frameworks is to hide complexity. I don’t think that Marks key point is regarding complexity. Can you show me a reference where he makes that statement?

          • Dave

            I think you are not clear on what a Service Locator is. This post by the aforementioned Mark Seemann explains why a DI Container is not a Service Locator per se (I’m referring to your sentence – Doesn’t that sound awfully a lot like a inversion of contol container). So, addressing your challenge, all you need to do is write a ControllerFactory which injects services into controllers – If you look how the Kernel is being used there, it is not as a Service Locator, it is as an infrastructure component.

          • I am well aware of who ploeh is and his view on the SL and containers. I had a discussion with him here:

            Regarding your challenge. Feel free to explain why that controller factory you mentioned do not use service location per the wikipedia definition (which I quoted).

          • The most obvious case as to why you would want SL in an application and not a framework is… SOA (how surprising).

            You have messages flowing. When the data is 1 you need service X, when the data is 2 you need service Y etc. The only ways to handle this is SL. You could use a switch statement or if/else soup but that’s just a poorman’s SL. Could you theoretically do this with constructor injection and an IOC container? Sure, but the trade off is you now need to embed message processing logic into the container registration which is the most invisible dependency ever. Mark Seeman talks about SL hiding intent, there’s nothing more hidden than logic inside an IOC container registration.

            Hell, i’m to the point that i prefer injecting concrete objects. Zero registration for containers. For testing I just mark public members virtual for functional/integration tests like an engine that needs data from the database. I just rewrite the virtual method of the DAL object to return Foo[]. I do my best to avoid all registration other than object lifetime. My IOC container registries are generally measured in single digit LOC.

          • C. Shea

            @dotnetchris:disqus Honestly, I don’t see how SOA has anything to do with how dependencies are resolved, either using a SL or a DIC.

            For instance, you could use an object following the Strategy pattern to determine what object can best satisfy the behavior based on the given inputs. The chose strategy implementation can then be provided by a factory (which could be an implementation of any one of the factory patterns: Factory Method, regular Factory, or even an Abstract Factory). And, the object receiving the request (let’s assume a WebAPI controller, for example), would have as dependencies the Strategy object (for determining what object will process the input) and the Factory (for creating the strategy implementation that will process the input), which can both be provided via constructor injection (assuming a best-case scenario, otherwise, depending on the architecture, let’s not forget about method injection or property/setter injection)–no service location _necessarily_ needed. (And of course, depending on design and architecture decisions, it may even be that you have a dependency on one object that functions as both a Strategy and a Factory, but to keep the discussion around abstract patterns, I’m using discrete objects in my discussion).

          • the Strategy pattern to determine what object can best satisfy the behavior based on the given inputs. The chose strategy implementation can then be provided by a factory

            Which is colloquially known as the Service Location pattern.

            This is merely injecting the locator as a dependency (which i full support). You should be able to step through all code in the debugger.

          • C. Shea

            In my opinion (and again, it’s my opinion and obviously not held by you :)–and that’s ok!!), that’s an abuse of the Service Locator pattern. Again, we disagree on this, but it’s ok to disagree–it’s just my opinion–I’m not necessarily right, nor am I wrong–and neither are you. We just differ on our choice of architecture/design.

            The point is, there is an alternative to using Service Locator–it is possible to use Dependency Injection. That’s all I wished to point out. 🙂

          • C. Shea

            @jgauffin As you said, an anti-pattern is a solution to “a recurring problem that is usually ineffective and risks being highly counterproductive” (your words), and I agree with that definition. By that definition, in no way does that mean that there’s _never_ a use for Service Location.

            I think what needs to be understood is the context in which we’re discussing the use of Service Location. For example, we both agree that framework development and application development are different. Frameworks generally consist of much more generalized code so as to maximize reusability. This flexibility in reuse implies that ways you might typically code something for an application may not apply, and vice versa. And so, for framework development, SL may be an appropriate choice in some situations (so, in that context, definitely not an “anti-pattern”). And so, yes, MVC, the framework, uses service location (i.e. the DependencyResolver). But, MVC is a framework, not an application. (As an aside with respect to the MVC Framework, as I said earlier, MVC 1.0 didn’t have the DependencyResolver and supported hooking up DI containers rather easily; so I question the need for SL within the MVC framework instead of providing more extensibility points which could be used as hooks for DI containers–but this is orthogonal to the discussion of whether SL vs. DI is appropriate for application development.)

            I took your original blog post, however, to be in the context of application development, and all of my comments have been from that point of view. (And I would consider both SOA-/REST-based systems to be applications, not frameworks.)

            So, to be clear, when I say “Service Location is an anti-pattern”, I mean this in terms of application development. So putting it in those terms, my statement would read:

            “For application development, provided the ability to equally choose to make use of either Service Location or Dependency Injection for dependency resolution, Service Location is an anti-pattern, providing a solution that is not as effective as Dependency Injection and risks of being highly counter-productive.”

            When writing applications, DI can accomplish the same thing as SL, but in a more intention revealing way in almost every situation. Naturally, if your toolset/framework is not capable of supporting DI (PowerShell is not very DI friendly), then SL may be a better choice. But, given all things equal (as it is with MVC), DI is (almost always) the better choice.

          • I’ve never said that I do not acknowledge the built-in extensibility points in ASP.NET MVC. In fact I think that they are great. But what do they have to do with this discussion?

            The default implementation in ASP.NET _do_ use service location. Constructor injection in the controllers would not work otherwise. all other solutions would increase complexity without giving any real gain.

          • C. Shea

            Only since v3. Prior to that, you used the built-in extensibility points present since v1 and still present today. And those extensibility points, as are demonstrated in various places on the web, not to mention in Mark’s book and at his blog, show exactly how they can be used to enable controller constructor injection. It just works–without having to use a service locator to bootstrap the process.

      • Reddy I. Bell

        “An inversion control container used through service location is the least complex solution for that problem” Hell yeeeah. Totally agree. This is the misconception people have. They limit the service locator pattern to what they see in the beginners tutorial. The service locator pattern used in conjunction with an IoC container is a very elegant solution that I have used extensively in many large scale projects without any gotcha in terms of maintainability.

  • C. Shea

    Good way to succinctly sum it up.

  • I strongly disagree. Service Locator is an anti pattern for one simple reason: It adds extra coupling and makes code difficult to test as a result. Given your very basic example:

    public class SomeService


    public void DoSomething()





    Here, if we want to test the doSomething method we must instantiate the service locator because the DoSomething method is coupled to both the ServiceLocator class and the ISomeRepository class. This is a classic Law of Demeter violation and all the problems that LoD highlights are apparent here. If the unit test for the DoSomething method fails, there’s no way for me as the developer to know whether it’s a bug in the ServiceLocator class or the repository. When I write the test, I have to instantiate the service locator and populate it with valid services, exposing the implementation of the DoSomething method to the test. The author of the test must know that the DoSomething method requires a ServiceLocator instance with a specific state.

    Wheras if the code looked like this:

    public class SomeService


    public void DoSomething(ISomeRepository repository)






    It’s clear to the person writing the test what the dependencies are and those dependencies can be mocked. Using the service locator, the service locator must be loaded with valid mocks, making for a very convoluted test case.

    And that’s assuming that the ServiceLocator is not a static method (which introduces even more problems!)

    • Jens

      Why would a non-explicit but required dependecy ever bite me at all? Can you make an example?

      • I prefer compiler errors before runtime errors.

        It can bite you if your tests doesn’t cover everything. If your testers miss something. It also forces you to always go into implementation details when you just want to use a class.

        You can’t control object lifetimes in the way that you can with constructor injection.

  • Reddy I. Bell

    I have a similar view and explain why this pattern is actually pivotal for OOP in this article :

  • Jens

    “Dependencies/information which is required should always be injected through the constructor.”

    Can somebody explain to me why everybody thinks this to be true?

    Clearly a missing required dependency is going to have the feature fail on first use anyway, so there’s no danger of a bug going to production here. Why, then, are people so adamant that the constructor clutter is worthwhile?

    • Are you saying that you always test all of the features (including all regression tests) on every release? That sounds like a very time consuming process.

      Constructor clutter (i.e. having several parameters) is a design smell. Break down the classes into smaller ones. Using service location just hides that smell.

  • I think it’s important to distinguish between abstract factory and service locator (both look pretty similar) not from internal or external mechanics of both, but how one is applied in the code-base. Mvc ControllerFactory might look like using service locator to obtain instance of controller, but that’s infrastructure code – that’s part of composition root, happening once. Components closer to architecture core (if we refer to onion or hexa here) should demand required dependencies or allow to be overwritten if there is a good local default.
    I’ve used ServiceLocator a lot. Was that disaster? Not at the beginning, because I wasn’t aware of better way out..

  • Alex Peter

    The key problem about Service locator as much as with anything that has acronyms is that developers think because so many people talk about it, it must be used in our next project, otherwise our project will not be modern and our manager is going to think that we are not following the latest standards. First is a bad opinion, second one is correct, he or she will think that.
    Once a developer goes into superficially understand what Service locator or dependency injector are for, he or she is adding it everywhere, where the pattern, neither the logic nor architecture calls for it, could.
    This IS what leads to anti-pattern and what I can read in last say 5 years projects is simply thinking upfront and counting on Service locator and dependency injection so it is more(!) used than inheritance.
    If you have one class and you know that you are not going to switch couple of locators meaning one interface is attached to one class always, you do not need either Service locator or dependency injection unless you truly want to handle scope but even that does not have to be done using any additional library.
    What I can see is that people are thinking that Service locator or dependency injection is the way of addressing service and they are adding it just for the sake of having it and especially thinking(!) that way, having that vocabulary.
    Instead of being used when needed people start using complicated grammatical structures for saying apple. And that on it s in own is the most horrible anti-pattern in existence.
    Everything starts turning into specialized expressions for nothing, like old C++ templates nobody except the specialist who wrote it and who might not be even alive understands.
    It is as if developers start a conspiracy of making the code as complicated as possible, because they are, well, smart. Simple code will make them look blunt or something. Instead of going into right opposite direction.
    Decoupling has become a necessary routine rather than a meaningful pattern. Debugging has become a real nightmare and I truly wonder what is going to happen in 5 years or so. Companies are and will keep failing because they cannot keep up, it is impossible to fix tons of code in any short time if you cannot understand it.
    And if we are this quick of adopting anything that looks modern and that people are talking about just for the sake of having it in our daily vocabulary, that on its own is something any company should be aware of, knowing that this pattern will ruin their chance of having one and the same product for more than 2-3 years.
    Keep the code as simple as possible. What has happened with that moral?