UnityContainer,子容器注入

时间:2008-12-10 01:27:21

标签: c# unity-container code-injection

我是Unity应用程序块的新手,并且试图实现以下内容有点困难。我有一个父子容器。当我解析子容器的新实例时,我想使用CreateChildContainer方法将新的UnityContainer注入构造函数。

public class RootContainer
{
    private IUnityContainer _container;

    public RootContainer()
    {
        _container = new UnityContainer();
        _container.RegisterType<IChildContainer, ChildContainer>();
    }
}

public interface IChildContainer { }

public class ChildContainer : IChildContainer
{
    private IUnityContainer _container;

    /* I want to inject the parent.CreateChildContainer() into this constructor */
    public ChildContainer(IUnityContainer container)
    {
        _container = container;
    }
}

1 个答案:

答案 0 :(得分:0)

我看到的最简单的解决方案是将ChildContainer的构造函数赋予父容器并在ctor中调用CreateChildContainer()方法:

public class ChildContainer2 : IChildContainer
{
    private IUnityContainer _container;

    public ChildContainer(IUnityContainer parent)
    {
        _container = parent.CreateChildContainer();
    }

    public IUnityContainer Container { get { return _container; } }
}

但是你为什么要让子容器成为服务呢?如果应用程序中的每个组件都需要自己创建一个子容器,那会不会更好?