I'm having problems getting a grasp on the practical sides of the concept depen开发者_Python百科dency injection using a IoC container. I had no problems implementing dependency injection on IController
classes using a ControllerFactory
. This is the default example in most IoC containers.
But now what? Is it just a matter of using IFoo bar = Container.Resolve<IFoo>;
everywhere in code instead of IFoo bar = new Foo();
?
update: According to gor this is not a good idea. Dependencies should be introduced using the constructor.
But what does this imply in practice?
interface IFoo {
IDependent dependency;
}
class Foo : IFoo {
public Foo(IDependent dependency) {
this.dependency = dependency;
}
}
I can only imagine doing this?!?
IFoo bar = new Foo(dependencyInstance);
Writing everywhere in your code IFoo bar = Container.Resolve<IFoo>
is not good idea. It is Service Locator pattern. The idea of DI to take out dependencies from your classes. The best way is take take introduce them in your classe's constructors. And request from Container
only root class. Other dependencies should be resolved automatically.
精彩评论