Ryan
Ryan

Reputation: 20116

How to get Unity Container from external configuration file?

In asp.net web api using Unity, I could register my services in UnityConfig.cs:

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();
        container.RegisterType<ITestService, TestService>();
        //above code needs to be read from config file

        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }
}

Now, I have a configuration file (located in the root of the project) where stores all those types to be registered:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
  <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>


<unity>

  <alias alias="ITestService" type="IMyServices.ITestService, IMyServices" />

  <container>

    <register type="ITestService" mapTo="MyServices.TestService,MyServices" />
 
  </container>
</unity>
</configuration>

How can I get container from this file?

Below is a similar question but has not been resolved: ASP.NET - Unity - Read configuration section from external configuration file

Upvotes: 1

Views: 1002

Answers (1)

Ryan
Ryan

Reputation: 20116

I find the solution to my problem which uses ExeConfigurationFileMap to specify the file path and load the specified configuration file explicitly.

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
        fileMap.ExeConfigFilename = "my/file/path";

        Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
        var section = (UnityConfigurationSection)configuration.GetSection("unity");

        IUnityContainer unityContainer = new UnityContainer();

        unityContainer.LoadConfiguration(section);

        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(unityContainer);
    }
}

Upvotes: 1

Related Questions