I've been looking at the Common Service Locator as a way of abstracting my IoC container but I've been noticing that some people are strongly against this type of this.
Do people recommend never using it? Always using it? or sometimes using it? If sometimes, then in what situations would you use it and what situations would you not use it.
The purpose of the Service Locator pattern is to return the service instances on demand. This is useful for decoupling service consumers from concrete classes. An implementation will consist of the following components: Client – the client object is a service consumer.
Service Locator holds reference of all types/objects an application needs. So whenever you need to use an instance of a type/class, ask service locator to provide the instance. Simply, the Service Locator uses a container to hold all references to class/type to instance/object mapping.
Service Locator is a dangerous pattern because it almost works. You can locate Dependencies from consuming classes, and you can replace those Dependencies with different implementations — even with Test Doubles from unit tests.
The main difference is how the dependencies are located, in Service Locator, client code request the dependencies, in DI Container we use a container to create all of objects and it injects dependency as constructor parameters (or properties). Dependency Injection doesn't require the use of a DI Container though.
Imagine you are writing library code to be used by 3rd party developers. Your code needs to be able to create service objects that these developers provide. However you don’t know which IoC container each of your callers will be using.
The Common Service Locator lets you cope with the above without forcing a given IoC on your users.
Within your library itself you may wish to register your own classes in the IoC, now it gets a lot harder as you need to choose a IoC for your own use that will not get in the way of your callers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With