Are service locators more than global variables / states?

To decouple the code, you can have a service locator, but it's not the same as global variables / state ?.

I know that these often end with interfaces, so you go through the interface and get a specific class, but still my question is.

For example:

class Something {

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

Here, the class requires MyType, which is created somewhere else, but instead of passing MyType down through chains (through constructors, etc.), it is obtained in this way.

I asked this question at an early stage of my professional career as a developer - before that I had not come across this model. Anthony nailed my opinion (and, therefore, now the selected answer) on the service locator - in fact, I consider them as anti-patterns, like others. The links provided are a good starting point - but to answer my own question after all this time, they act like a global state and should be avoided. Prefer a standard dependency injection;)

+3
source share
3 answers

, . , . .

. Locator?

- -

+2

, , , .

, " " . . . .

- , . , .

+3

- . "" , "" . .

You can change the argument. If you need to access a service in your application, which template would you use to access it without tying it to a specific implementation. There are not many alternatives.

Some resources are inherently "global" for your application, they accept the operating system, file system, windows system, ...

The discussion is more philosophical than solving the problem. Anyway, hope this helps.

+1
source

Source: https://habr.com/ru/post/1710207/


All Articles