开发者

Dependency injection practical information?

开发者 https://www.devze.com 2023-02-10 18:29 出处:网络
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 IControll

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消