Service Locator seems like a pretty useful concept and I'd like to implement it in my app. However, I have a few questions about how it should be implemented and how it should be used in conjunction with other programming paradigms.
Should the SL manage the service it is storing? That is, when the SL gets destroyed, should it also destroy the service itself, or should it leave that to whoever registered the service?
What about Dependency Injection? Now that I have an SL is there any point in passing the SL around as a parameter or should I access it globally? After all, much of the whole purpose of DI is covered by SL as well, and I wouldn't like to clutter a lot of my functions with one more parameter.
Service Locator is a well-known pattern, and since it was described by Martin Fowler, it must be good, right? No, it's actually an anti-pattern and should be avoided.
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.
The service locator design pattern is used when we want to locate various services using JNDI lookup. Considering high cost of looking up JNDI for a service, Service Locator pattern makes use of caching technique. For the first time a service is required, Service Locator looks up in JNDI and caches the service object.
What are Service Design Patterns? Service design patterns are the basic building blocks that make up services — things like proving your identity, sharing your information, making a payment, or getting a notification.
You would think I wrote this article (I didn't), considering how often I refer to it:
Service Locator is an Anti-Pattern
Dependency Injection makes your dependencies explicit. Service Location buries them in the implementation, and creates a hard dependency on your locator.
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