我在使用Castle Windsor注入一系列服务时遇到问题xml配置。我已经按照this链接进行了很好的解释,但不知怎的,它对我不起作用。这是我正在使用的代码:
class Program
{
static void Main(string[] args)
{
IWindsorContainer container = new WindsorContainer();
container.Install(Castle.Windsor.Installer.Configuration.FromAppConfig());
var consumer = container.Resolve<Consumer>();
}
}
public class Consumer
{
public Consumer(IFoo[] foos)
{
foreach (IFoo foo in foos)
foo.Foo();
}
}
public interface IFoo
{
void Foo();
}
public class Foo1 : IFoo
{
public void Foo() { }
}
public class Foo2 : IFoo
{
public void Foo() { }
}
这是app.config:
<castle>
<components>
<component id="Foo1" service="Test.IFoo, Test" type="Test.Foo1, Test" />
<component id="Foo2" service="Test.IFoo, Test" type="Test.Foo2, Test" />
<component id="Consumer" service="Test.Consumer, Test">
<parameters>
<foos>
<array>
<item>${Foo1}</item>
<item>${Foo2}</item>
</array>
</foos>
</parameters>
</component>
</components>
</castle>
奇怪的是,我得到的错误如下:
Can't create component 'Test.Consumer' as it has dependencies to be satisfied.
'Test.Consumer' is waiting for the following dependencies:
- Service 'Test.IFoo[]' which was not registered.
为什么期望IFoo []作为服务?这有任何意义吗?或者也许我所指的链接不再适用于当前版本的Windsor(我在3.1.0上)?
答案 0 :(得分:4)
再次回答我自己的问题(抱歉; - ):
原来,解决方案非常简单 - 一旦你知道。添加ArrayResolver作为子解析器不仅使这个工作:
static void Main(string[] args)
{
IWindsorContainer container = new WindsorContainer();
container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel));
container.Install(Castle.Windsor.Installer.Configuration.FromAppConfig());
var consumer = container.Resolve<Consumer>();
}
但即使只是简单配置,因为您不必设置实例:
<configuration>
<configSections>
<section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
</configSections>
<castle>
<components>
<component id="Foo1" service="Test.IFoo, Test" type="Test.Foo1, Test" />
<component id="Foo2" service="Test.IFoo, Test" type="Test.Foo2, Test" />
<component id="Consumer" service="Test.Consumer, Test"/>
</components>
</castle>
</configuration>
一如既往,事实证明Castle Windsor很棒,但文档不是很好,而且你会在网上找到许多不同的版本,这些版本不会让它变得更容易......