使用Castle Windsor注入依赖关系

Yog*_*hav 0 c# castle-windsor

考虑我有一个界面.

interface Interface<A> {}  
Run Code Online (Sandbox Code Playgroud)

现在我有2个实现此接口的类:

class ClassOne<A>: I<A> {}
class ClassTwo<A>: I<A> {}  
Run Code Online (Sandbox Code Playgroud)

现在我想在第三个类中使用这两个类.

class child
{
    child(Interface<A> objCA,Interface<A> objCB)
    {}
}  
Run Code Online (Sandbox Code Playgroud)

我无法使用Castle Windsor为子类注入依赖项.即使我注入它,它只传递一个对象到它们所有.那么如何使用Castle Windsor解决这个问题呢?

pio*_*est 5

您可以使用Castle Windsor集合/数组/列表解析器来完成此操作.

看看:https://github.com/castleproject/Windsor/blob/master/docs/resolvers.md

这样,您将能够以略微不同的语法获得相同的行为.

像这样配置容器:

container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));
Run Code Online (Sandbox Code Playgroud)

注册CA和CB如下:

container.Register(Component.For<IA>().ImplementedBy<CA>());
container.Register(Component.For<IA>().ImplementedBy<CB>());
Run Code Online (Sandbox Code Playgroud)

并将你的班级改为:

class child
{
    child(IEnumerable<IA> objs)
    {}
}
Run Code Online (Sandbox Code Playgroud)