The Service Locator Pattern in Swift

Avoid Dependency Injection entirely!

Image for post
Image for post
Photo by QuickOrder on Unsplash

The service locator pattern is designed to encapsulate the processes invovled in obtaining a service with a strong layer of abstraction.

Prerequisites:

The explanation

Service locator has a central registry known as the service locator, that on request returns the data required to perform a task. The service locator returns instances of services when they are requested by the service consumers or service clients.

The Service Locator pattern does not describe how to instantiate serveices, rather it describes a way to register services and locate them.

Image for post
Image for post

The Example

Here is an example. This example is written with a Playground in mind: In fact the tests are included (and will work ina Playground).

What is happening here is that we are using a Dictionary to register services. These services can be added or removed from the list, and basically lets us “get” the services from this dictionary.

Advantages and Disadvantages

Advantages:
— Application optimize themselves by adding or removing items from the ServiceLocator
— The only link between parts of the application becomes the registry of services

Disadvantages:
— The registry itself can be difficult to maintain
— When dependencies are missing there may be run-time errors

In fact it is common to set up the service locator itself as a Singleton, and then mocks can be inserted into the Service Locator (for example) with a code snippet:

ServiceLocator.shared.addService(MockServer())

This does, however
- Introduce a Singleton to your code
- it isn’t clear is the client of a server is using the Mock instance or real instance — so your testing is not repeatable

Conclusion

Service Locator is often considered to be an “Anti-Pattern”, as are “Singletons”. If you want to go in this direction you need to make sure that you understand what they are, and how they might impact your code.

I hope this article has gone some way in helping you decide this for yourself.

If you’ve any questions, comments or suggestions please hit me up on Twitter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store