External Config File?

Aug 14, 2008 at 12:59 AM
Is it possible to load Unity configuration from a file other than web/app.config?  I'd like to do this similar to the way Enterprise Library allows you to load from an external file, but I'm not sure if it's possible.

Thanks.
Aug 15, 2008 at 8:53 AM
Edited Aug 15, 2008 at 8:59 AM
Yes you can load from any xml file but you have to do it programmatically whereas you can reference external files in the app.config in something like castle windsor

So if your unity config was in a file called Live.xml

var map = new ExeConfigurationFileMap { ExeConfigFilename = “Live.xml” };
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var section = (UnityConfigurationSection)config.GetSection(“unity”);
IUnityContainer container = new UnityContainer();
section.Containers["liveContainer"].Configure(container);

There is an example of this on my blog at http://aardvarkblogs.wordpress.com/unity-container-tutorials/4-switching-configurations/ but the code formatting has got borked a little(will need to sort that later)
Aug 18, 2008 at 10:05 PM
In my blog I provide a demo program that will automatically load a configuration file that has the same name of the currently running assembly/module; in the case of the demo I am writing it using the CompositeWPF however it can be applied to any Unity application; an excerpt of the code that does the work follows:

namespace ShellApp.Infrastructure.Base
{
    public class ModuleBase : IModule
    {
        protected IUnityContainer Container { get; set; }
        protected IRegionManager RegionManager { get; set; }

        public virtual void Initialize()
        {
            RegisterViewsAndServices();
        }

        protected virtual void RegisterViewsAndServices()
        {
            UnityConfigurationSection section = GetUnitySection();
            section.Containers[GetType().Name].Configure(Container);
        }

        protected UnityConfigurationSection GetUnitySection()
        {
            Configuration config = OpenConfigFile(GetType().Name);
            return (UnityConfigurationSection)config.GetSection("unity");
        }

        protected Configuration OpenConfigFile(string baseName)
        {
            ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = baseName + ".config";
            return ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
        }