The Ghost of Service Locator — Why the weak ones confuse it with Factory Pattern!

Yaz
3 min readJan 6, 2024

I have found some readers confusing the Factory pattern with the Service Locator pattern when a Factory Pattern is used for Dependency Injection. So here is the difference between a Factory Pattern and a Service Locator pattern.

In my recent blog, I wrote about how to efficiently Inject your dependencies for Objects of the same kind, and a reader commented on how I have called out the Service Locator pattern and yet Implemented another Service Locator.

To be honest, that line in the blog about the service locator was deliberately added for the weak ones, but it does not always work, does it?

So here is my explanation of why using Factory for dependency injection is not the same as using a service locator pattern.

Factory Pattern Vs Service Locator

The Functional Differences

  • A Factory creates objects for you when requested.
  • A Service Locator returns objects that may already exist, i.e. services that may exist somewhere for you.

The Design Differences

If you have used a service locator or a factory pattern you must have seen the following interfaces:

--

--