简体   繁体   中英

Explain “Dependency Injection vs Service Location” when using IoC containers

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); } 

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM