@credit samueleresca.net

Service Locator vs Dependency Injection

Nay Lin Aung
4 min readDec 1, 2018

This article will try to clarify about the differences between Service Locator and Dependency Injection.

That’s why it won’t describe “what-is” detail definition of these patterns.

Dependency Injection

Dependency Injection is a difficult-to-explain subject if the programmer haven’t met the dependency maintenance problems in his real-world programmer life. At the first sight of Dependency Injection, someone might even say it’s dull and overkill.

Dependency Injection is all about the abstraction. It is the implementation detail of the Dependency Inversion Principle from SOLID which strongly suggests that

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend upon details. Details should depend upon abstractions.

Generally, it can be understand as avoiding the hard-coded dependencies. This is a very good blog that explains and demonstrate what is all about Dependency Injection.

Service Locator

Service Locator pattern is also one of a way to implement the Dependency Inversion (caution: not Inject) Principle. According to the name, it is really intended to locate Service (e.g. DataService).

A service locator usually contains references to the services and that encapsulates the logic that locates them. What means “encapsulates the logic” ? For example, think about the DataService Locator. If the app cannot get the Internet connection, Service Locator will check and provide LocalStorage DataService. Otherwise, it will provide CloudStorage DataService.

The Service Locator pattern does not describe how to instantiate the services. It describes a way to register services and locate them. Typically, the Service Locator pattern is combined with the Factory pattern and/or the Dependency Injection pattern. This combination allows a service locator to create instances of services.

That is good to read detail article about the Service Locator Pattern.

What is the Difference?

Their difference seem so small, so that some people even said there is no difference at all. It is completely based on your personal assumption. There is no universal-truth viewpoint on this subject matter.

In Consuming matters:

For me, they are in clearly different shapes. In Service Locator, the class is still responsible for creating its dependencies. It uses the service locator to figure out how to create the dependencyဗ. For example,

Class Customer {
private iDataService _dataService;
private ServiceLocator _serviceLocator;

public Customer() {
_dataService = _serviceLocator.DataService();
}
}

With Dependency Injection, the class is given it’s dependencies. It neither knows, nor cares where they come from. For example,

Class Customer {
private iDataService _dataService;

public Customer(dataService) {
_dataService = dataService;
}
}

Martin Fowler states that:

With service locator the application class asks for it explicitly by a message to the locator. With injection there is no explicit request, the service appears in the application class — hence the inversion of control.

In Implementation matters:

Service Locator pattern is very similar to IoC container and sometimes even use IoC container in his own code setup (for dependency issues). Dependency injection is normally done with constructor, method and property injection if we don’t use IoC container.

It’s very important to understand IoC, IoC container and Dependency injection are under the same intention but not the equivalent in implementation.

IoC is the umbrella term for the ways how control flow of the program (especially object creation) is inverted. There are several ways to implement IoC as service locator, event, delegate and dependency injection.

The IoC container is the framework to help the Dependency Injection complexity. These days people becoming so much used to already cooked frameworks. Because the frameworks already include IoC container for dependency injection, they think that Dependency Injection and IoC container as the only one. The IoC container is complete self-existed separate Design Pattern. It’s really up to the programmer using the container to make the dependency injection.

How the Service Locator and Dependency Inject works together

In Galasoft’s MvvM Light framework, these two design patterns are combined beautifully in ViewModelLocator base class.

As in the following code sample,

public class ViewModelLocator
{
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default );
if (ViewModelBase.IsInDesignModeStatic) {
SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
} else {
SimpleIoc.Default.Register<IDataService, DataService>();
}
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<SecondViewModel>();
}public MainViewModel Main
{
get
{
return SimpleIoc.Default.GetInstance<MainViewModel>();
}

Service Locator pattern is used for locating ViewModel for each view. And Dependency Injection Container is used for resolving the particular ViewModel during locating process.

Conclusion

Which one is better to use is completely rely on the context of the system. Generally, Service Locator pattern is more suitable to use in existing code base as it don’t force to change the public interface.

But dependency injection pattern is more readable and clear. And it also widely used and gain more popularity in several programming languages and frameworks. On the other side, Service Locator pattern is just popular in Microsoft world specifically associated with C# WPF and Asp.net MVC framework.

Whatever, both of them are implementation details of the principle that encourage to use Abstractions over Concretion. Their main purpose is to make the system design “loosely coupled”, “extensible” and “flexible”.

--

--

Nay Lin Aung

Technical Lead at uab Bank's Fintech & Digital Payment.