【问题标题】:Castle Windsor: How to wire up a component to a factory property rather than methodCastle Windsor:如何将组件连接到工厂属性而不是方法
【发布时间】:2008-10-10 15:32:04
【问题描述】:

我有以下组件

public class MyTimer : IMyTimer {
  public MyTimer(TimeSpan timespan){...}
}

时间跨度应由属性 ISettings.MyTimerFrequency 提供。

如何在 Windsor 容器 xml 中连接它? 我以为我可以这样做:

    <component id="settings"
                service="MySample.ISettings, MySample"
                type="MySample.Settings, MySample"
                factoryId="settings_dao" factoryCreate="GetSettingsForInstance">
        <parameters><instance_id>1</instance_id></parameters>
    </component>

    <component id="my_timer_frequency"
                type="System.TimeSpan"
                factoryId="settings" factoryCreate="MyTimerFrequency" />

    <component id="my_timer" 
                service="MySample.IMyTimer, MySample"
                type="MySample.MyTimer, MySample">
        <parameters><timespan>${my_timer_frequency}</timespan></parameters>         

但我收到一个错误,因为当工厂设施需要一个方法时,MyTimerFrequency 是一个属性。

这里有一个简单的解决方案吗?我是否以错误的方式处理整个事情?

编辑:肯定有解决办法,请看下面我的回答。

【问题讨论】:

    标签: .net xml inversion-of-control castle-windsor


    【解决方案1】:

    解决方案实际上是在梦中想到的。请记住,属性不是 CLR 构造,而是 C# 语法糖。如果您不相信我,请尝试编译

    public class MyClass {
      public object Item {
        get;
      }
      public object get_Item() {return null;}
    }
    

    导致错误:类型“TestApp.MyClass”已经保留了一个名为“get_Item”的具有相同参数类型的成员

    由于 Xml 配置在编译后在运行时被保存,我们可以通过绑定到它编译到的方法来简单地绑定到 factoryCreate 属性,因此上面的示例变为:

    <component id="my_timer_frequency"
                            type="System.TimeSpan"
                            factoryId="settings" factoryCreate="get_MyTimerFrequency" />
    

    瞧!

    有人投票赞成,因为我无法将其标记为答案。

    【讨论】:

    【解决方案2】:

    最简单的解决方案不是添加一个包装属性的方法吗?

    【讨论】:

    • 我有很多设置,而且必须包装每个设置的想法不是很吸引人。
    猜你喜欢
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    相关资源
    最近更新 更多