12
在温莎国际奥委会容器中,是否可以注册一个我已经拥有实例的类型,而不是让容器创建它?您可以在Windsor容器中注册一个类型的现有实例吗?
在温莎国际奥委会容器中,是否可以注册一个我已经拥有实例的类型,而不是让容器创建它?您可以在Windsor容器中注册一个类型的现有实例吗?
容器的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);
}
作为一个更新,这种技术现在已经过时。使用`container.Register(Component.For().Instance(myT));`代替。 –
eouw0o83hf
2012-04-10 13:36:07