Dependency Injection - Part 7 - Service Locator Pattern

Service locator pattern is one of the most commonly used patterns. In general, this pattern is used along with other patterns like Adapter Pattern, Observer Pattern, Dependency Injection Principles and many more. In this post, however, we will be talking about its use with dependency injection, which is one its many uses.

Introduction
 
The service locator pattern works as a middleman between the application and the services used by it. The intent is to unbind the application from the services it uses. The application rather requests the locator to provide a service it requires at any point in time. However, an application may have a dedicated or a generic locator depending on the application requirements. A dedicated service locator serves the requests for a particular service, whereas a generic locator serves all the requests.
 
Scenario

In our previous post, we used Autofac in order to manage the dependencies of Commerce class. It's equally important to note, that our Commerce class may have some methods which use either of the dependencies or do not use any of them at all. And therefore, instantiating all the dependencies at once doesn't seem to be a good idea.

At this instant, a better approach to such a scenario would be, to instantiate a dependency "only" when it is required. Unlike instantiating all the dependencies at once, a service locator instantiates a dependency/service as and when required. Consequently, saving the runtime manager from the burden of managing in-memory dependency objects, which may never be used in the application again.

Implementing a Generic Service Locator

As can be seen in the code below, our Commerce class has multiple dependencies. The container instantiates all these dependencies for our first request of Commerce class object. And therefore, we use the service locator pattern to optimize our code for such scenarios.
  1. public class Commerce  
  2. {  
  3.     private readonly PaymentProcessor _paymentProcessor;  
  4.     private readonly NotificationManager _notificationManager;  
  5.     private readonly Logger _logger;  
  6.   
  7.     public Commerce(PaymentProcessor paymentProcessor, NotificationManager notificationManager, Logger logger)  
  8.     {  
  9.         _paymentProcessor = paymentProcessor;  
  10.         _notificationManager = notificationManager;  
  11.         _logger = logger;  
  12.     }  
  13.   
  14.     public void ProcessOrder(Order order)  
  15.     {  
  16.         decimal paidAmount = order.UnitPrice * order.Quantity;  
  17.         bool paymentSuccessful = _paymentProcessor.ProcessPayment(paidAmount);  
  18.               
  19.         if(paymentSuccessful)  
  20.         {  
  21.             _notificationManager.NotifyCustomer(notification: "payment successful");  
  22.         }  
  23.         else  
  24.         {  
  25.             _notificationManager.NotifyCustomer(notification: "payment failed");  
  26.             _logger.Log(errorMessage: "payment failed");  
  27.         }  
  28.     }  
  29. }  
We have a generic service locator as IServiceLocator, which takes a generic at method level. There can be many ways in which the locator locates the requested service. For instance, it may use some configuration file or use a DI container (as in our case) to locate the service requested. 
  1. public interface IServiceLocator  
  2. {  
  3.     TContract Locate<TContract>();  
  4. }  
  5.   
  6. public class ServiceLocator : IServiceLocator  
  7. {  
  8.     public TContract Locate<TContract>()  
  9.     {  
  10.         return Program.Container.Resolve<TContract>();  
  11.     }  
  12. }  
Additionally, we have new implementation of the Commerce class as NewCommerce class, in order to better understand the use of a locator. It is equally important to note that we need to explicitly register the ServiceLocator as IServiceLocator with the container. 
  1. public class NewCommerce  
  2. {  
  3.     private readonly IServiceLocator _serviceLocator;  
  4.     public NewCommerce(IServiceLocator serviceLocator)  
  5.     {  
  6.         _serviceLocator = serviceLocator;  
  7.     }  
  8.   
  9.     public void ProcessOrder(Order order)  
  10.     {  
  11.         decimal paidAmount = order.UnitPrice * order.Quantity;  
  12.         bool paymentSuccessful = _serviceLocator.Locate<PaymentProcessor>().ProcessPayment(paidAmount);  
  13.         NotifyCustomer(paymentSuccessful);  
  14.     }  
  15.   
  16.     private void NotifyCustomer(bool paymentSuccessful)  
  17.     {  
  18.         var notifier = _serviceLocator.Locate<NotificationManager>();  
  19.         if (paymentSuccessful)  
  20.         {  
  21.             notifier.NotifyCustomer("payment successful");  
  22.         }  
  23.         else  
  24.         {  
  25.             notifier.NotifyCustomer("payment failed");  
  26.             _serviceLocator.Locate<Logger>().Log("payment failed");  
  27.         }  
  28.     }  
  29. }  

 Summary

  • As a result of implementing the service locator pattern, our NewCommerce class has a single dependency of IServiceLocator.
  • The DI container does not instantiate all the services used by the NewCommerce class.
  • The service locator instantiates a dependency only when it is required.
  • Using a service locator with DI is one of its many uses.
  • A service locator may use some configuration file, in order to locate the service.

Related Articles


Similar Articles