Load Unity mappings from an XML File

inversion-of-control, ioc-container, unity-container

Solution

You can use XML configuration with Unity, you can even mix the design time config (XML) and runtime (code) configuration.

However the Design-Time Configuration uses the `UnityConfigurationSection` and the config loading is only supported through this so you need to do a little more work if you want to have the config in different (e.g. not app.config or web.config) file.

Luckily you can find a sample in the documentation under: Loading the Configuration from Alternative Files section:

using System.Configuration;

var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = "unity.config" };

Configuration configuration =
    ConfigurationManager.OpenMappedExeConfiguration(fileMap,                  
                                                    ConfigurationUserLevel.None);

var unitySection = (UnityConfigurationSection)configuration.GetSection("unity");

var container = new UnityContainer().LoadConfiguration(unitySection);

Problem

I would like to be able to load the following into Unity: ``` UnityContainer.RegisterType<ClientRegistrationVM, ClientRegistrationVMDesign>(); ``` By loading it via an XML File. Here would be some psudo code of what I would like to have happen. ``` FileStream unityMappings = new FileStream(@".\UnityMappings.xml", FileMode.Open) UnityContainer.CreateFromXML(unityMappings); unityMappings.Dispose(); ``` And the UnityMappings.xml file would contain the mappings and the dlls that the types are in. Is what I want even possible with Unity? Has anyone done this before?

Original source