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

I want to integrate Unity into my application and I want it to use an external configuration file

Unity Initialization Code

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); 

In addition, I have an external configuration file for unity named "unity.config" with the following contents

 <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 that on the line where I want to load singleSection, 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 track the code, in line

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

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

Any idea how to reference the configuration file from a web folder?

Thanks.

+4
source share
4 answers

Have you tried adding the <configuration> and <configSections> to your configuration file?

0
source

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

Your external configuration file should also start with a <configuration> , not a <unity>

0
source

I do not know if you have decided this. In Visual Studio, you must provide the following file properties for "Unity.config":

  • Assembly action โ†’ "Content"
  • Copy to output directory โ†’ "Copy if new" or "Always copy"

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

0
source

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

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

The server is a property of the page or uses HttpContext.Current.Server.

0
source

Source: https://habr.com/ru/post/1396704/


All Articles