ASP.NET - Unity - Read configuration section from external configuration file

此生再无相见时 提交于 2021-01-27 07:08:35

问题


I want to integrate Unity in my app and I want it to use an external config file

The Unity initialization code is

var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = "unity.config" };
System.Configuration.Configuration configuration =
ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

// *** problem starts here ***
var unitySection = (UnityConfigurationSection)configuration.GetSection("unity");
var container = new UnityContainer().LoadConfiguration(unitySection);

Also I have external config file for unity, named "unity.config" with the following content

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <alias alias="IEmailConfigurator" type="Server.Common.Interfaces.IEmailConfigurator, Server.Common" />
  <alias alias="EmailConfigurator" type="Server.Common.EmailConfigurator, Server.Common" />

  <namespace name="Server.Common.Interfaces" />
  <namespace name="Server.Common" />

  <container>
    <register type="IEmailConfigurator" mapTo="EmailConfigurator" />
  </container>
</unity>  

The problem is, in the line where I want to load unitySection, GetSection() returns null.

What could be the problem?


EDIT

I added

<configuration>
    <configSections>
        <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
        </configSections>

However, now when I trace through code, in line

System.Configuration.Configuration configuration = //...

The configuration variable in initialized that FilePath property is C:\Program Files (x86)\IIS Express\unity.config, and not my own unity.config file

Any idea how to reference the config file from web folder?

Thank you.


回答1:


http://msdn.microsoft.com/en-us/library/ff660935%28v=pandp.20%29.aspx

Your external config file must also start from <configuration> tag, not <unity> tag




回答2:


Did you try to add the <configuration> and <configSections> element to your config file?




回答3:


I don't know if you solved this yet. In Visual Studio, you have to ensure the following file properties for "Unity.config":

  • Build Action -> "Content"
  • Copy to Output Directory -> "Copy if newer" or "Copy Always"

I suggest "Copy Always" to ensure the current Unity configuration is always present after a build.




回答4:


To access the web folder, use the HttpServerUtility.MapPath method.

var mappedConfig = Server.MapPath("~/unity.config");

Server is a property of the Page, or use HttpContext.Current.Server.



来源:https://stackoverflow.com/questions/9300214/asp-net-unity-read-configuration-section-from-external-configuration-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!