I'm converting a Castle/Monorails application into a Unity/Asp.NET MVC one, I'm stuck in trying to converting this component configuration:
<component
id="ComponentBaseConfiguration"
service="MyFakeNamespace.BOL.IConfiguration, MyFakeAppDll"
type="MyFakeNamespace.BOL.ConfigurableConfiguration, MyFakeAppDll">
<parameters>
<!-- Setting Configuration (Dictionary<string,string>)-->
<Config>
<dictionary>
<entry key="localHost">#{LocalHost}</entry>
<entry key="contentHost">#{ContentHost}</entry>
<entry key="virtualDir">#{VirtualDir}</entry>
</dictionary>
</Config>
</parameters>
seems that Unity supports Array but not Dictionary, I would like to do something like this:
<unity>
<containers>
<container>
<types>
<type name="ComponentBaseConfiguration" type="MyFakeNamespace.BOL.IConfiguration, MyFakeAppDll" mapTo="MyFakeNamespace.BOL.ConfigurableConfiguration, MyFakeAppDll">
<typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">
<property name="Config" propertyType="System.Collections.Generic.Dictionary`2[[System.String, mscorlib], [System.String, mscorlib]],mscorlib">
<dictionary>
<entry key="localHost">127.0.0.1</keyedValue>
<entry key="contentHost">\\content</keyedValue>
<entry key="virtualDir">/</keyedValue>
</dictionary>
</property>
</typeConfig>
</type>
</types>
</container>
</containers></unity>
How can I achieve something like this?
Unity cannot serialize standard dictionaries. This means that they won't show or be edited in the inspector and they won't be instantiated at startup. A classic workaround is to store the keys and values in separate arrays and construct the dictionary at startup.
Unity cannot serialize dictionaries by default. Make a struct/class that contains a key and a value, and expose a list of those objects.
Dictionaries — Unity C# The Dictionary type steps away from arrays and lists by storing value pairs in each element, instead of single values. These elements are referred to as key-value pairs: the key acts as the index, or lookup value, for its corresponding value. Unlike arrays and lists, dictionaries are unordered.
I think you have to use the method-element to archive this. It´s not nice but a workaround.
Your type must define a method Add(string key, string value) which the unity container uses to inject the values.
<method name="Add">
<param name="key" parameterType="string">
<value value="localHost"/>
</param>
<param name="value" parameterType="string">
<value value="127.0.0.1"/>
</param>
</method>
Unity definitely does not support dictionaries for container configuration. See Build Dictionaries using Unity container?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With