wex*_*man 2 xml arrays castle-windsor castle inject
我在通过Castle Windsor使用xml配置注入一系列服务时遇到问题。我已经按照此链接进行了很好的解释,但是以某种方式它对我不起作用。这是我正在使用的代码:
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() { }
}
Run Code Online (Sandbox Code Playgroud)
这是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>
Run Code Online (Sandbox Code Playgroud)
奇怪的是,我得到的错误如下:
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.
Run Code Online (Sandbox Code Playgroud)
为什么期望IFoo []作为服务?这有任何意义吗?或者也许我所指的链接在当前版本的Windsor(我在3.1.0上)上不再起作用?
再次回答我自己的问题(对不起;-):
事实证明,解决方案非常简单-一旦知道。将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>();
}
Run Code Online (Sandbox Code Playgroud)
但是,甚至只需配置即可,因为您不必设置实例:
<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>
Run Code Online (Sandbox Code Playgroud)
一如既往,事实证明温莎城堡很棒,但文档却不行,而且您会在网络上找到示例的许多不同版本不会使它变得更容易...