문제

Windsor IOC 컨테이너에서 컨테이너가 인스턴스를 생성하도록 하는 대신 이미 인스턴스가 있는 유형을 등록할 수 있습니까?

도움이 되었습니까?

해결책

컨테이너의 커널 속성에는 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);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top