title: What's the difference between the Dependency Injection and Service Locator patterns?
body: <p>Both patterns seem like an implementation of the principle of inversion of control. That is, that an object should not know how to construct its dependencies.  </p>
  
  <p>Dependency Injection (DI) seems to use a constructor or setter to "inject" it's dependencies. </p>
  
  <p><strong>Example of using Constructor Injection:</strong> </p>
  
  <pre><code>//Foo Needs an IBar
  public class Foo
  {
    private IBar bar;
  
    public Foo(IBar bar)
    {
      this.bar = bar;
    }
  
    //...
  }
  </code></pre>
  
  <p>Service Locator seems to use a "container", which wires up its dependencies and gives foo it's bar. </p>
  
  <p><strong>Example of using a Service Locator:</strong></p>
  
  <pre><code>//Foo Needs an IBar
  public class Foo
  {
    private IBar bar;
  
    public Foo()
    {
      this.bar = Container.Get&lt;IBar&gt;();
    }
  
    //...
  }
  </code></pre>
  
  <p>Because our dependencies are just objects themselves, these dependencies have dependencies, which have even more dependencies, and so on and so forth. Thus, the Inversion of Control Container (or DI Container) was born.  Examples: Castle Windsor, Ninject, Structure Map, Spring, etc.)</p>
  
  <p>But a IOC/DI Container looks <strong>exactly</strong> like a Service Locator.  Is calling it a DI Container a bad name?  Is an IOC/DI Container just another <strong>type</strong> of Service Locator? Is the nuance in the fact that we use DI Containers mostly when we have many Dependencies?</p>