Dependency Injection, Service Locator, Inversion of Control

Updated: 10 January 2025

From Stackoverflow

Constructor injection

public class Foo
{
  private IBar bar;

  public Foo(IBar bar)
  {
    this.bar = bar;
  }
}

Service locator

public class Foo
{
  private IBar bar;

  public Foo()
  {
    this.bar = Container.Get<IBar>();
  }
}

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.

—Martin Fowler.

  1. An object should not know how to construct its dependencies.
  2. The Inversion of Control Container is also known as a Dependency Injection Container.

Leave a comment