在Windsor Installer中使用强类型配置参数

Ily*_*gan 0 c# dependency-injection castle-windsor castle inversion-of-control

我一直在使用自定义配置对象安装Windsor容器.这似乎很简单,但显然有一些重要但我没有得到.如果你能帮我填补这个空白,我将不胜感激.

我有一个配置类:

class MyConfiguration
{
    int SomeIntValue;
    DateTime SomeDateValue;
    Action<string> SomeActionValue;
}
Run Code Online (Sandbox Code Playgroud)

我想将这些配置值作为构造函数参数传递给已注册的实现.我想注册看起来应该是这样的:

public class MyInstaller : IWindsorInstaller
{
   public void Install(IWindsorContainer container, IConfigurationStore store)
   {
      container.Register(Component.For<IFoo>.ImplementedBy<Foo>
        .Parameters(Parameter.ForKey("parameter1").Eq( INSERT VALUE HERE (?) );
   }
}
Run Code Online (Sandbox Code Playgroud)

那么我如何获取这些值并将它们传递给安装程序?我应该使用这个IConfigurationStore参数吗?如果是这样,我该如何填写它以及我该怎么做呢?

此外,似乎所有配置对象都只能存储字符串值,那么如何传递非字符串的值(例如DateTime)?

谢谢,周末愉快.

Mar*_*ann 8

在绝大多数情况下,您不必显式注册构造函数参数.该自动布线功能应能自动照顾这对你.这将使您的代码不那么脆弱,从而更易于维护.

因此,您可以做的最好的事情就是在容器中注册MyConfiguration.如果这只有一个类型的注册(正常方案),容器可以明确地解决该类型的任何请求.因此,如果另一个类将MyConfiguration作为构造函数参数,Castle Windsor将自动为您匹配它们.您无需明确指定.

但是,在某些情况下,您需要显式分配特定参数值.对于这些情况,您可以使用ServiceOverrides.这可能看起来像这样:

container.Register(Component.For<MyConfiguration>().Named("myConfig"));
container.Register(Component
    .For<IFoo>()
    .ImplementedBy<Foo>()
    .ServiceOverrides(new { parameter1 = "myConfig" }));
Run Code Online (Sandbox Code Playgroud)

如果需要分配特定实例,可以改为使用DependsOn:

var myConfig = new MyConfig();
container.Register(Component
    .For<IFoo>()
    .ImplementedBy<Foo>()
    .DependsOn(new { parameter1 = myConfig }));
Run Code Online (Sandbox Code Playgroud)