Jeff Fol Jeff Fol - 4 months ago 15
C# Question

Loading Custom Configuration Section from DLL Reference

In our project we have defined a custom configuration section which works fine when being referenced in the project. Now we are trying to reference this same configuration section from a dll which is added as a reference. From the code in this dll we can access ConfigurationManager.AppSettings with no problems but getting errors when accessing configuration entry.

Web.config code

<section name="mailManager" type="FullNamespace, NameSpace" />

<mailManager prop1="propVal1">
<prop2 key1="keyVal1" key2="keyVal2" key3="keyVal3" />
<prop3 key1="keyVal1" key2="keyVal2" />
</mailManager>


In the dll which is referencing it is throwing the following error when trying get the configuration section. This section exists in both the solution for the dll and main solution code base.

var mailManagerConfigSection = ConfigurationManager.GetSection("mailManager") as EmailManagerConfigSection;


The error we get is error CS0433: The type 'EmailManagerConfigSection' exists in both 'namespace1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'namespace2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

The dll reference exists in the same bin directory that the main code is running from. Is there anyway to have the dll refer to the main EmailManagerConfigSection which has the values rather than whatever is local to the dll which is null? We do not want to introduce any dll.config file.

Answer

Configuration sections must be defined, loaded, and referenced from an executable, not from a DLL.

You can keep the source code for the config file in the dll project in your solution space, but wherever the compile of the dll puts the config file, the app.config for the host executable (that references the dll) must declare and specify that file in it's app.config [ApplicationName.Exe.config] Just add the appropriate <ConfigSections> <section> element and actual section element for the config into the host executables app.config.

Comments