Unity加载配置文件的两种方式
1、当前AppDomain的配置文件(App.config或Web.config,通过AppDomain.CurrentDomain.SetupInformation.ConfigurationFile获得):
1 IUnityContainer unityContainer = new UnityContainer(); 2 unityContainer.LoadConfiguration();
LoadConfiguration默认会加载没有命名的container,可以通过传递特定的containerName加载指定的container。
配置示例:
<?xml version=”1.0″ encoding=”utf-8″ ?> <configuration> <configSections> <section name=”unity” type=”Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration”/> </configSections> <unity xmlns=”http://schemas.microsoft.com/practices/2010/unity”> <container> </container> <container name=”container1″> </container> </unity> </configuration>
2、显示加载指定的配置文件,通过ExeConfigurationFileMap指定文件路径:
1 ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); 2 fileMap.ExeConfigFilename = “Unity.config”; 3 4 Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); 5 UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection(“unity”); 6 7 IUnityContainer unityContainer = new UnityContainer(); 8 9 unityContainer.LoadConfiguration(section);
LoadConfiguration是IUnityContainer的扩展函数,在Microsoft.Practices.Unity.Configuration.dll中的Microsoft.Practices.Unity.Configuration namespace下定义的UnityContainerExtensions。