Using common unity configurations for mutiple projects

Jul 2, 2014 at 12:49 AM
Hi, I've got multiple projects that share most of the unity configurations and each has some specific mapping. Is there a way to share a unity configuration section or a unity container with out having to duplicate all the configurations in all projects ?

If not, what is the way to extend the configuration section to have multiple sources that get merged to one configuration that has all configuration sources combined ?

Thanks in advance.
Jul 2, 2014 at 7:45 AM
You can use the configSource attribute to point to a common unity config file. The config file will have to be in the same folder or a subfolder as the application.

So use an app.config:
<?xml version="1.0" encoding="utf-8" ?>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>

  <unity configSource="unity.config" />
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
Create and deploy unity.config:
  <unity xmlns="">
    <assembly name="ClassLibrary1"/>
    <namespace name="ClassLibrary1"/>
      <register type="IDoctor" mapTo="Doctor" />
And then just load the configuration:
IUnityContainer container = new UnityContainer();
Unity also supports multiple LoadConfiguration() calls with each one merging the results into the container which may be closer to what you are looking for. Here's an example:
IUnityContainer container = new UnityContainer();

// Load default app.config/web.config

IDoctor doctor = container.Resolve<IDoctor>();

// Now load common config by opening another config file
ExeConfigurationFileMap fileMap =
        new ExeConfigurationFileMap();
// You may want to map to your own exe.comfig file here.
fileMap.ExeConfigFilename = @"C:\UnityConfig\app.config";
System.Configuration.Configuration config =

// Get the unity config section...
UnityConfigurationSection unityConfig = 
    config.GetSection(UnityConfigurationSection.SectionName) as UnityConfigurationSection;

// ...and use it to configure the container

// Resolve new mapping only in the second config
doctor = container.Resolve<IDoctor>("eye");

Randy Levy
Enterprise Library support engineer
Support How-to
Marked as answer by amrmahdi on 7/3/2014 at 11:55 AM