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" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>

  <unity configSource="unity.config" />
  
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>
Create and deploy unity.config:
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <assembly name="ClassLibrary1"/>
    <namespace name="ClassLibrary1"/>
    <container>
     
      <register type="IDoctor" mapTo="Doctor" />
    </container>
  </unity>
And then just load the configuration:
IUnityContainer container = new UnityContainer();
container.LoadConfiguration();
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
container.LoadConfiguration();

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 =
    ConfigurationManager.OpenMappedExeConfiguration(fileMap,
    ConfigurationUserLevel.None);

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

// ...and use it to configure the container
container.LoadConfiguration(unityConfig);

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

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