xml - 通过 XML 统一配置字典

标签 xml dependency-injection inversion-of-control unity-container

如何使用 Unity 容器通过 XML 配置字典? 这有效:

<register type="System.Collections.Generic.Dictionary[string,int]" >
<constructor>
    <param name="capacity">
    <value value="10" />
    </param>
</constructor>
</register>

但我需要能够在 XML 配置中添加元素。

最佳答案

上次我尝试这样做时,我不得不使用自定义转换器并为字典值发明我自己的解析器。我不记得是哪项研究让我到达那里的,但这是注册和相应的转换器类。

<type type="IRequestPolicy" mapTo="RequestPolicyCatalog, Assembly">
   <constructor>
     <param name="dictionary" type="System.Collections.Generic.KeyValuePair`2[System.Int32,System.String][], mscorlib">
       <array>
         <value value="1, 'unauthorized'" typeConverter="Assembly.IntStringKeyValueConverter, fore.Core"/>
         <value value="2, 'activation'" typeConverter="Assembly.IntStringKeyValueConverter, Quofore.Core"/>
         <value value="3, 'routing'" typeConverter="Assembly.IntStringKeyValueConverter, Quofore.Core"/>
       </array>
     </param>
   </constructor>
</type>
public class IntStringKeyValueConverter : System.ComponentModel.TypeConverter {
    public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) {
        return this.ConvertFrom(context, culture, value);           
    }

    public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType) {
        return sourceType == typeof(string);
    }

    public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, Type destinationType) {
        return destinationType == typeof(KeyValuePair<int, string>);
    }

    public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
        var comma = ((string)value).IndexOf(',');
        if(comma < 0)
            throw new InvalidOperationException("Invalid string, must contain ',' between values");
        var number = int.Parse(((string)value).Substring(0, comma));
        var str = ((string)value).Substring(comma).Trim(new[] { ',', '\'', ' ' });

        return new KeyValuePair<int, string>(number, str);
    }
}

关于xml - 通过 XML 统一配置字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5154315/

相关文章:

c# - 使用依赖注入(inject)框架时的抽象工厂

java - 模拟其属性在测试类构造函数中使用的依赖项

c# - 使用 new 运算符创建对象/依赖项与使用 DI 容器

android - 将 String 或 InputStreamReader 转换为 InputSource

java - JSONObject JSON 数组长度

unit-testing - 具有文件系统依赖性的单元测试代码

asp.net-mvc - 有没有更好的方法在asp.net-mvc中进行IOC?

inversion-of-control - 使用 Autofac 有什么优点和缺点

python - 使用带有转义字符作为参数的 XML 使用 WSDL url

java - 您可以从 JAX-WS @WebMethod 返回一个数组吗?