为什么不通过你的IoC容器? [英] Why not pass your IoC container around?

查看:98
本文介绍了为什么不通过你的IoC容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此AutoFac最佳做法页面( http://code.google.com) / p / autofac / wiki / BestPractices ),他们说:

On this AutoFac "Best Practices" page (http://code.google.com/p/autofac/wiki/BestPractices), they say:

不要通过集合
给组件访问容器,或将其存储在公共静态属性中,或者在全局IoC类上执行Resolve()等功能可以使用依赖注入的目的。这样的设计与服务定位器模式更相似。
如果组件对容器有依赖关系,请查看它们如何使用容器来检索服务,并将这些服务添加到组件(依赖注入)构造函数参数中。

那么,一个组件动态地实例化一个更好的方法是什么呢?他们的第二段不包括可能需要创建的组件将取决于系统的状态的情况。或者当组件A需要创建X个组件B时。

So what would be a better way to have one component "dynamically" instantiate another? Their second paragraph doesn't cover the case where the component that "may" need to be created will depend on the state of the system. Or when component A needs to create X number of component B.

推荐答案

要抽象出另一个组件的实例化,可以使用工厂模式:

To abstract away the instantiation of another component, you can use the Factory pattern:

public interface IComponentBFactory
{
    IComponentB CreateComponentB();
}

public class ComponentA : IComponentA
{
    private IComponentBFactory _componentBFactory;

    public ComponentA(IComponentBFactory componentBFactory)
    {
        _componentBFactory = componentBFactory;
    }

    public void Foo()
    {
        var componentB = _componentBFactory.CreateComponentB();

        ...
    }
}

然后可以将该实现注册到IoC容器中。

Then the implementation can be registered with the IoC container.

容器是组合对象图的一种方法,但它并不是唯一的方法。这是一个实现细节。保持没有这种知识的对象将它们从基础设施问题中解脱出来。它也使得他们不必知道要解决的依赖关系的哪个版本。

A container is one way of assembling an object graph, but it certainly isn't the only way. It is an implementation detail. Keeping the objects free of this knowledge decouples them from infrastructure concerns. It also keeps them from having to know which version of a dependency to resolve.

这篇关于为什么不通过你的IoC容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆