Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Config dictionary for unity via XML

How can I configure a dictionary via XML with Unity container? This works:

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

But I need ability to add elements in XML config.

like image 661
vitali Avatar asked Dec 28 '22 00:12

vitali


1 Answers

Last time I tried to do that I had to use a custom converter and invent my own parser for dictionary values. I don't remember which research got me there, but here is the registration and the corresponding converter class.

<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);
    }
}
like image 185
Igor Zevaka Avatar answered Jan 08 '23 22:01

Igor Zevaka