2

In Jason's answer to Dependency Injection vs Service Location:

Right:

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

Is the following sentence true?

The point of using IoC frameworks as StructureMap or Unity is, that we can do

  1. dependency injection

    public Foo(container->GetInstance(IBar)) 
    {
         this.bar = bar; 
    }
    

    which is better than doing:

  2. service locator

    public Foo(Container container) 
    {
         this.bar = container->GetInstance(IBar); 
    }
    
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Martin
  • 83
  • 1
  • 9
  • *"In the Jason replay"* - do you mean [Jason's answer](https://stackoverflow.com/a/4985582/3001761)? I don't see that sentence in it. – jonrsharpe Aug 06 '18 at 13:16
  • jonrsharpe, yes, I menat the part "public Foo(Bar bar) { this.bar = bar;}", which is as fourth option there. – Martin Aug 06 '18 at 15:01

1 Answers1

3

The point of dependency injection is that you can do

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

and decouple the class Foo from the Bar class. You then use StructureMap, Unity, or any other of the 20+ dependency injection containers to configure which class or instance you want to use for each contract (=interface, optionally plus name) and let the DI container resolve all dependencies.

You do that because it allows you to unit test your class Foo effectively by mocking its dependencies. You usually do not explicitly inject the dependencies yourself.

In my opinion, dependency injection usually works best, if you only use it as a one-time thing. That is, you resolve your main application service at the beginning of your appliaction including all of its dependencies and then use the initialized network of service objects while the application is running.

You avoid the service locator (which is your second code example) because 1. it ties you to a specific DI container and 2. you are hiding the dependency to IBar.

Georg
  • 5,626
  • 1
  • 23
  • 44
  • Georg , thanks for your quick answer. I just wanted to add, if someone is looking for more information, here is a one good article https://adamcod.es/2013/11/25/service-locator-vs-dependency-injection-container.html Among many others which made me more and more confused and let more opened questions then answered, it was the first one, that explained the thing. As an example please look at https://www.codeproject.com/Articles/1239583/WebControls/WebControls/ . The guy is describing problems of IoC, presenting servce locator without knowing it - see his arguing with wkempf in comments. – Martin Aug 06 '18 at 15:17