2011-05-13 56 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!"))));