Dependency Inversion: Service Locator or Dependency Injection

On software engineering, SOLID is an acronym meaning:

  1. Single Responsibility: the notion that an object should have only a single responsibility.
  2. Open/Closed: the notion that “software entities … should be open for extension, but closed for modification”.
  3. Liskov’s principle: the notion that “objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program”.
  4. Interface Segregation: the notion that “many client specific interfaces are better than one general purpose interface.”
  5. Dependency Inversion: the notion that one should “Depend upon Abstractions. Do not depend upon concretions.”

This is very important in Object-Oriented software design.

Service Locator and Dependency Injection are just implementations of Dependency Inversion Principle.

The important principle is “Depend upon Abstractions, not upon Concretions”. This will make your souftware design “loosely coupled”, “extensible”, “flexible”.

Let’s see some “strongly coupled code” (“MyComponent” depends on “Logger”):

public class MyComponent
{
  public MyComponent()
  {
  :
  }
  public void DoSomeWork()
  {
    var logger = new Logger();
  :
  }
}

We can change it to use an “interface“, but someone must provide the “implementation“:

public class MyComponent
{
  public MyComponent()
  {
  :
  }
  public void DoSomeWork()
  {
    ILogger logger = ...; // who’s going to provide this?
  :
  }
}

We have 2 options: Service Locator and Dependency Injection.

//Service Locator pattern
public class MyComponent
{
    public MyComponent()
    {
        :
    }
    public void DoSomeWork()
    {
        ILogger logger = ServiceLocator.GetService();
        :
    }
}

On Service Locator “you have a dependency resolver component (aka “ServiceLocator“) that typically takes a type (commonly an interface) and returns an instance of a concrete type that implements that interface. The match between the type that is passed and the concretely-instantiated type is hidden in the implementation of the locator component”.

//Dependency Injection pattern
public class MyComponent
{
  private ILogger _logger;
  public MyComponent(ILogger logger)
  {
    _logger = logger;
  }
  public void DoSomeWork()
  {
    // Use the logger component here
    _logger.Log();
   :
  }
}

In this case, the MyComponent class receives the ILogger component to use from the outside world. Surrounding classes will take care of the initialization of the logger before passing it down to MyComponent. This is the essence of the Dependency Injection pattern.

Martin Fowler states: “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.”

Also : “The choice between Service Locator and Dependency Injection is less important than the principle of separating service configuration from the use of services within an application. “

So, it’s up to you which one to use.

Regarding ASP.Net MVC and Dependency Inversion, Dino Esposito has a great post here, in which, in fact, I’ve mainly based this post.

Dino Esposito states: “ASP.NET MVC is designed with several extensibility points, but generally it lacks a comprehensive support for dependency injection. A service locator is probably the most effective way of making an existing framework more loosely coupled by the addition of new extensibility points, because it is the least intrusive solution.”

He also states: “A dependency resolver is just a service locator integrated with the ASP.NET MVC codebase. Resolvers are a way to add the implementation of the Dependency Inversion principle into an existing (large) codebase. For the size and complexity of the codebase, the use of Dependency Injection is less appropriate because it would have required changes at various levels in the public API.”

References:

ASP.NET MVC: Resolve or Inject? That’s the Issue… by Dino Esposito

Inversion of Control Containers and the Dependency Injection pattern by Martin Fowler

InversionOfControl by Martin Fowler

Designing Reusable Classes  by Ralph E. Johnson & Brian Foote

WCF Service Dependency Injection by Oran Dennison

SOLID (object-oriented design)

Dependency inversion principle

Dependency injection

About these ads

Deja un comentario

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

Seguir

Recibe cada nueva publicación en tu buzón de correo electrónico.

Únete a otros 78 seguidores

A %d blogueros les gusta esto: