inversion-of-control - CaSTLe Windsor 是否允许解析值类型?

标签 inversion-of-control castle-windsor castle

我正在尝试将参数传递到需要 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/

相关文章:

.net - 温莎城堡 : How do you add a call to a factory facility not in xml?

c# - 在 Winforms 中使用 IoC 时如何不绕过容器

mvvm - Caliburn.Micro + Unity 2.1 + MVVM : example code

c# - 在 MVC 中设置 CaSTLe Windsor

nhibernate - 我在 nuget 中哪里可以找到 nhibernate.bytecode.caSTLe dll?

java - 使用 Spring IoC 配置 SSL ReSTLet 服务器?

c# - 使用 CaSTLe Windsor 在服务类的构造函数中使用参数化构造函数初始化类

asp.net-web-api - 使用 Windsor CasSTLe 拦截 webpi2 调用

c# - 城堡 ActiveRecord "Could not compile the mapping document: (string)"

asp.net-mvc - 使用 MVC 和流利的 Nhibernate,如何在将 ViewModel 上的唯一字段绑定(bind)到我的域对象并保存它们之前验证它们?