Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are service locators not just global variables/state?

In order to decouple code you can have service locater's but is this not the same as global variables/state?.

I know these often run off interfaces, so you pass in an interface and get a concrete class back but still my question stands.

For example:

class Something {

    void DoSomething() {
        IMyType myType = ServiceLocator.GetSerivceTypeOf(IMyType);
    }
}

Here the class requires MyType which is created somewhere else, but rather than passing MyType down through the chains (via constructors etc...) it is acquired in this manner.

I asked this question early in my professional career as a developer - prior to then I'd not come across this pattern. Anthony has nailed my opinion (and therefore is the selected answer now) on service locator's - in fact I see them as anti-patterns like others. The links provided are a good starting point - but to somewhat answer my own question after all this time, they act as global state and should be avoided. Prefer standard dependency injection ;)

like image 867
Finglas Avatar asked Jun 10 '09 21:06

Finglas


People also ask

What is the difference between Service Locator and Dependency Injection?

To implement the IoC, you have the choice of two main patterns: Service Locator and Dependency Injection. The Service Locator allows you to "resolve" a dependency within a class and the Dependency Injection allows you to "inject" a dependency from outside the class.

Why is service locator an Antipattern?

It can be difficult to give up on the idea of directly controlling Dependencies, and many developers take Static Factories to new levels. This leads to the Service Locator anti-pattern. A Service Locator supplies application components outside the Composition Root with access to an unbounded set of Dependencies.

Is service locator inversion of control?

With service locator the application class asks for it explicitly by a message to the locator. With injection there is no explicit request, the service appears in the application class – hence the inversion of control.

Why do people hate global variables?

The reason global variables are bad is that they enable functions to have hidden (non-obvious, surprising, hard to detect, hard to diagnose) side effects, leading to an increase in complexity, potentially leading to Spaghetti code.


1 Answers

Yes they are global variables. Sophisticated ones, but they still have the same basic drawbacks. For that reason, dependency injection is preferable.

For more detailed discussion of the alternative of constructor injection, see also the question What’s the difference between the Dependency Injection and Service Locator patterns?

And other web pages Singletons are Pathological Liars and Dependency Injection pattern

like image 135
Anthony Avatar answered Sep 21 '22 03:09

Anthony