In the Windsor IOC container is it possible to register a type that I've already got an instance for, instead of having the container create it?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
There is a AddComponentInstance method on the Container's Kernel property.
From the Unit Tests:
[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);
}