2011-05-13 62 views
0

我如何限制类型解析在子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>();      
    } 
} 
+0

您希望派生容器拥有自己的一组注册吗?所以有些类只能从父容器派生? – PVitt 2011-05-13 11:55:21

+0

它不是派生容器它是子容器。它的重要区别 – void 2011-05-13 12:20:03

+0

是的,我的意思是小孩的容器。抱歉混淆。那么你希望子容器拥有它自己的一组注册? – PVitt 2011-05-13 12:25:50

回答

1

这确实是错误的做法。认真重新考虑你的容器层次结构,你在这里可能不需要层次结构。

但是,如果你已经死了,你可以伪造它。使用一个抛出异常的InjectionFactory重新注册该子类型。

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