Build Dictionaries using Unity container?

Jul 22, 2009 at 7:31 PM

I know I can build up an array using unity, but is it possible also build up a dictionary using a Unity container as well, if so, can you provide an example?

Thanks

Jul 24, 2009 at 5:05 AM

There's nothing directly to do this in the container. You could use the static factory extension to new up a dictionary and fill it in if you wanted.

The main reason we don't have this is we couldn't figure out what the container semantics would be. What would you want the container to do when presented with a dependency on Dictionary<SomeKey, SomeValue>?

 

Feb 5, 2010 at 8:59 PM
<type ... to="MyTypeServer">
   <typeConfig>
      <property Name="Converters"  KeyType"string" ValueType="IConverter">
          <entry>
             <key>csv</key>
             <value><dependency name="csvConverter"/></value>
          </entry>

          <entry>
             <key>xml</key>
             <value><dependency name="xmlConverter"/></value>
          </entry>
      </property>
   </typeConfig>
</type>


<type name="csvConverter" from="IConverter" to="MyCsvConverter"> 
</type>

<type name="xmlConverter" from="IConverter" to="MyXmlConverter"> 
</type>


In our code for MyTypeServer.cs:

public class MyTypeServer
{
       public IDictionary<string, IConverter> Converters
       {
           set; 
           private get;
       }

       public void DoConversion(string fileName)
       {
            string fileType = Path.GetFileExtension(fileName);
            IConverter converter = Converters[fileType];

            if (converter != null)
                converter.DoConversion(fileName);
            ..
            ...
       }

}
 
This is a quick pseudo code of the type of stuff we can have with dictionary. YOu see, we are not storing IDictionary<,>
in the container, but we can use it to build up a dictionary to be used by the consuming class.

I think Spring.NEt has something like this, and probably castle. So, this is nothing alien.