2008-09-18 41 views

回答

13

容器的Kernel属性上有一个AddComponentInstance方法。

从单元测试:

[Test] 
    public void AddComponentInstance() 
    { 
     CustomerImpl customer = new CustomerImpl(); 

     kernel.AddComponentInstance("key", typeof(ICustomer), customer); 
     Assert.IsTrue(kernel.HasComponent("key")); 

     CustomerImpl customer2 = kernel["key"] as CustomerImpl; 
     Assert.AreSame(customer, customer2); 

     customer2 = kernel[typeof(ICustomer)] as CustomerImpl; 
     Assert.AreSame(customer, customer2); 
    } 

    [Test] 
    public void AddComponentInstance_ByService() 
    { 
     CustomerImpl customer = new CustomerImpl(); 

     kernel.AddComponentInstance <ICustomer>(customer); 
     Assert.AreSame(kernel[typeof(ICustomer)],customer); 
    } 

    [Test] 
    public void AddComponentInstance2() 
    { 
     CustomerImpl customer = new CustomerImpl(); 

     kernel.AddComponentInstance("key", customer); 
     Assert.IsTrue(kernel.HasComponent("key")); 

     CustomerImpl customer2 = kernel["key"] as CustomerImpl; 
     Assert.AreSame(customer, customer2); 

     customer2 = kernel[typeof(CustomerImpl)] as CustomerImpl; 
     Assert.AreSame(customer, customer2); 
    } 
+6

作为一个更新,这种技术现在已经过时。使用`container.Register(Component.For ().Instance(myT));`代替。 – eouw0o83hf 2012-04-10 13:36:07

相关问题