我正在尝试将参数传递到需要 System.TimeSpan 的组件中。我只能让'long ticks' ctor 来解决。
这是配置文件的一个片段:
<component id="timeInForce" type="System.TimeSpan, mscorlib">
<parameters>
<hours>0</hours>
<minutes>15</minutes>
<seconds>0</seconds>
</parameters>
</component>
<component id="FooSettings" type="Foo.FooSettings, Foo">
<parameters>
<tif>${timeInForce}</tif>
</parameters>
</component>
这是异常(exception)情况:
Castle.MicroKernel.Handlers.HandlerException : Cant create component 'timeInForce'
as it has dependencies to be satisfied.
timeInForce is waiting for the following dependencies:
Keys (components with specific keys)
- ticks which was not registered.
为组件参数传递一个刻度值是有效的,如下所示:
<parameters><tif>0</tif></parameters>
但这违背了目的。
最佳答案
发生的事情(据我所知)是 ticks 属性被错误地识别为强制参数(因为它属于参数数量最少的构造函数),即使所有值类型都有默认的无参数构造函数。
然而,即使您提供了额外的参数(即 ticks),匹配最多参数的构造函数候选者仍然会被选中,因此您可以通过在参数列表中包含 ticks 来解决这个问题:
<component id="timeInForce"" type="System.TimeSpan, mscorlib">
<parameters>
<ticks>0</ticks>
<hours>0</hours>
<minutes>15</minutes>
<seconds>0</seconds>
</parameters>
</component>
这是一个验证它是否有效的快速测试(通过城堡树干):
string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<castle>
<components>
<component id=""timeInForce"" type=""System.TimeSpan, mscorlib"">
<parameters>
<ticks>0</ticks>
<hours>0</hours>
<minutes>15</minutes>
<seconds>0</seconds>
</parameters>
</component>
</components>
</castle>";
WindsorContainer container = new WindsorContainer(
new XmlInterpreter(new StaticContentResource(xml)));
TimeSpan span = container.Resolve<TimeSpan>("timeInForce");
Assert.AreEqual(new TimeSpan(0, 15, 0), span);
但是,我建议而不是您使用的方法是实现您自己的类型转换器,如 castle documentation 中所讨论的那样.
这样您就可以开发自己的时间跨度速记形式,即“15 分钟”或“2 小时 15 分钟”或您喜欢的任何内容 - 让您的配置更易于阅读和维护,并解决您当前遇到的问题。
关于inversion-of-control - CaSTLe Windsor 是否允许解析值类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/267483/