Reputation: 83
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
dependency injection
public Foo(container->GetInstance(IBar))
{
this.bar = bar;
}
which is better than doing:
service locator
public Foo(Container container)
{
this.bar = container->GetInstance(IBar);
}
Upvotes: 2
Views: 1069
Reputation: 5771
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
.
Upvotes: 3