Unity约束类型\实例解析在子容器中

时间:2011-05-13 11:22:10

标签: .net unity-container

我如何在子unityContainer中限制类型解析?

E.g

internal interface ITestInterface
{}
public class Test:ITestInterface
{}
class A
{
    public A(ITestInterface testInterface)
    {    
    }
}

class Program
{
    static void Main(string[] args)
    {

        var container = new UnityContainer();

        Test test = new Test();
        container.RegisterInstance<ITestInterface>(test);

        var childContainer = container.CreateChildContainer();
        //shoudl resolved normally
        container.Resolve<A>();
        //should throw exception!
        //because i want restrict resolving ITestInterface instance from parent container!            
        childContainer.Resolve<A>();                       
    }
}

1 个答案:

答案 0 :(得分:2)

这真的是错误的做法。认真重新考虑您的容器层次结构,您可能根本不需要层次结构。

然而,如果你已经死定了,你可以假装它。使用引发异常的InjectionFactory重新注册子类型。

childContainer.RegisterType<A>(
    new InjectionContructor(c => throw new InvalidOperationException(
        "No type A for you!"))));