你能在Windsor Container中注册一个类型的现有实例吗?

Cam*_*and 12 .net c# vb.net castle-windsor inversion-of-control

在Windsor IOC容器中是否可以注册一个我已经拥有实例的类型,而不是让容器创建它?

Chr*_*nal 13

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 作为更新,此技术现已弃用.使用`container.Register(Component.For <T>().Instance(myT));`代替. (6认同)