2008-11-06 37 views
3

我想传递一个参数到需要System.TimeSpan的组件中。我只能得到'长蜱'来解决。Castle Windsor是否允许值类型的解析?

这里是配置文件的一个片段:

<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> 

这是例外:

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> 

但这打破了目的。

+0

似乎参数元素名称与MicroKernel期望的不匹配:tif代替预期的timeInForce。 $ {timeInForce}应该工作 – smoothdeveloper 2010-06-21 08:50:22

回答

4

发生了什么(从我可以看到的情况),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); 

不过,我会建议而不是你的使用方法是实现自己的类型转换器,如讨论。

通过这种方式,您可以开发自己的速记形式,例如“15m”或“2h15m”或任何您喜欢的内容 - 让您的配置更容易阅读和维护,并解决您当前遇到的问题。