您可以在 Windsor 容器中注册类型的现有实例吗?
-
01-07-2019 - |
题
在 Windsor IOC 容器中,是否可以注册我已经获得实例的类型,而不是让容器创建它?
解决方案
Container 的 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);
}
不隶属于 StackOverflow