首页 / 知识

关于c#:可以在Windsor容器中注册类型的现有实例吗?

2023-04-17 01:18:00

关于c#:可以在Windsor容器中注册类型的现有实例吗?

Can you register an existing instance of a type in the Windsor Container?

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


容器的内核属性上有一个AddComponentInstance方法。

从单元测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
[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);
}


类型注册内核属性

最新内容

相关内容

猜你喜欢