I will cover most of the topics about Dependency Injection in this Series. This series contains four parts as follows

Let start with Part 4: Understanding how Service Locator different from Dependency Injection

Before Understanding how Service Locator different from Dependency Injection [Please read previous parts to get complete understanding of Dependency Injection], we understand what is Service Locator is and how it is implemented with some native example.

Service Locator is also a pattern which uses to de-couple the components dependency as similar like Dependency Injection, but in Service Locator pattern, the component/class is not injected with its dependent service objects dynamically via. Framework but we should explicitly call for respective service object as per need.

Let’s look at some simple example below to demonstrate working with Service Locator pattern and will see different types of implementation with this pattern.

public class Employee 
    { 
        public string FirstName { get; set; } 
        public string LastName { get; set; } 
        public string EmpNumber { get; set; } 
        public decimal Salary { get; set; } 
    } 
  
    public interface IEmployeeRepository 
    { 
        IEnumerable<Employee> GetAllEmployees(); 
    } 
  
    public class EmployeeRepository : IEmployeeRepository 
    { 
        public IEnumerable<Employee> GetAllEmployees() 
        { 
            //some db logic to fetch Employees information 
            return (new List<Employee>()); 
        } 
    } 
  
    public static class ServiceLocator 
    { 
        public static IEmployeeRepository employeeRepository = null; 
  
        public static IEmployeeRepository GetEmployeeRepository() 
        { 
            return new EmployeeRepository("<<connection string>>"); 
         } 
         
    } 
  
    public class EmployeeBusiness 
    { 
        public EmployeeBusiness() 
        { 
            IEmployeeRepository employeeRepository = ServiceLocator.GetEmployeeRepository(); 
            var lstEmp = employeeRepository.GetAllEmployees(); 
  
            Console.ReadLine(); 
        } 
    }

The above example is self explanatory, let’s assume all different classes are placed in different components including interface. Now, as observed the EmployeeBusiness class constructor is explicitly calling ServiceLocator class to get resolve and return the EmployeeRepository instance.

This EmployeeBusiness class is now decoupled and not tightly coupled with its calling EmployeeRepository implementation class as is we achieve with dependency injection pattern.

This Service Locator can be make more generic such that we can send the type of object expected will return the same. Following are the changes to above example

public EmployeeBusiness() 
      { 
          IEmployeeRepository employeeRepository = ServiceLocator.GetRepository<IEmployeeRepository>(); 
          var lstEmp = employeeRepository.GetAllEmployees(); 

          Console.ReadLine(); 
      }

Service Locator vs Dependency Injection

Both are the patterns targeted to achieve loose coupling between different components for more maintainability and testability.

We cannot say which pattern is good either Service Locator or DI as its purely depending on the requirement. The only difference between these patterns is injecting the required service objects implicitly by the framework in case of DI and requesting the service objects on demand explicitly in the case of Service Locator.

Still we can use Unity container Framework for Service Locator pattern too and take advantage of lifetime management feature. Whenever we call the GetRepository method in ServiceLocator class, we can resolve the requested object using Unity container Resolve method as below

public static class ServiceLocator 
    { 
        public static UnityContainer unityContainer = GetUnityContainer(); 
        public static IRepository GetRepository<T>() 
        { 
            return unityContainer.Resove<T>(); 
        } 
    }

Hybrid Solution 

We can combine both DI and Service Locator pattern at one place and take advantage of it. How?

This Service Locator class object can be injected from the EmployeeBusiness Constructor using Dependency Injection and resolve the respective services via. Service Locator pattern as we done in the above example.

With this explanation, we are done with all the core concepts of IoC pattern. This series we are able to understand what is IoC, DI and Service Locator patterns, how to implement in real time examples and also its advantages and disadvantages.