Using Configuration Manager.GetSection with Configuration Manager.OpenExe
I have an executable that consumes DLL’s through MEF. I am successfully loading each DLL’s config file's appsettings keys using
var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
return appConfig.AppSettings.Settings["Version"].Value;
Now I want to make it so the DLL allows for adhoc items in the DLL’s config file.
So I added this to the config file
<configSections>
<section name="AdHocRules" type="BusinessRules.AdHocConfiguration, BusinessRules" />
</configSections>
<AdHocRules BaseRuleNumber="ConfigEx1" RuleN开发者_JAVA百科ame="Config Example" EffectiveDate="5/1/2010" Value="Example" IsValid="true"/>
And I created a class to read the above. And when I run this in a test console app that is not consuming the DLL – so everything is complied together and a single app config everything works fine
BUT – I want to use the DLL’s config file and I keep getting an error
Unable to cast object of type 'System.Configuration.DefaultSection' to type 'BusinessRules.AdHocConfiguration
This is not working; - it's throwing the above
var cm = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
AdHocConfiguration adhoc = (AdHocConfiguration)cm.GetSection("AdHocRules");
And this is code – adhoc is null because it is not loading from the correct config file
AdHocConfiguration adhoc = (AdHocConfiguration)ConfigurationManager.GetSection("AdHocRules");
BusinessRules.Rule r = new BusinessRules.Rule();
r.BaseRuleNumber = adhoc.baserulenumber;
r.RuleName = adhoc.rulename;
r.EffectiveDate = adhoc.effectivedate;
r.Value = adhoc.value;
Any ideas?
In order to use the OpenExeConfiguration method, the configuration files for the other DLLs need to reside in the same directory as the executable file as they mention in the MSDN Reference.
You might need a post-build event to move the config files, but it does work.
Also you might want to use Assembly.GetAssembly(some type loaded by MEF).Location; rather than Assembly.GetExecutingAssembly().Location, depending on how you are using it.
I have a sample project where I load parts using MEF, and read their config files.
Let me know if you still have trouble
精彩评论