简体   繁体   中英

Read AppSettings from MEF plugin

I would like to access the values in the ConfigurationManager.AppSettings object from a MEF plugin which has its own app.config file.

However, the keys from the app.config file are not present in AppSettings after the plugin is loaded. The keys from the application loading the plugin are still present.

I noticed that using a Settings.settings file allows this behaviour, via the app.config file, so the file must be being loaded somehow.

My plugin looks like:

[Export(IPlugin)]
public class Plugin
{
    public Plugin()
    {
        // reads successfully from app.config via Settings object
        var value1 = Settings.Default["Key1"];

        // returns null from app.config via ConfigurationManager
        var value1 = ConfigurationManager.AppSettings["Key2"]
    }
}

The app.config looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="..." >
      <section name="Plugin.Settings" type="..." />
    </sectionGroup>
  </configSections>

  <appSettings>
    <add key="Key2" value="Fails" />
  </appSettings>

  <applicationSettings>
    <Plugin.Settings>
      <setting name="Key1" serializeAs="String">
        <value>Works</value>
      </setting>
    </Plugin.Settings>
  </applicationSettings>
</configuration>

I can manually load the app.config file with:

var config = ConfigurationManager.OpenExeConfiguration("Plugin.dll");
var value = AppSettings.Settings["Key2"].Value

but this seems more like a workaround than a solution.

Is there a way to access a MEF plugin's <appSettings> directly, from inside the plugin? If not, what is recommended?

By default the ConfigurationManager loads the .config for the entry assembly, ie the assembly that started the currently executing process.

The correct way to do this would be something like this:

[Export(IPlugin)]
public class Plugin
{
    public Plugin()
    {
        var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
        var value = config.AppSettings.Settings["Key2"].Value;
    }
}

This would make the plugin automatically open the .config for the DLL it was compiled in, and fetch values from there.

I'd recommend you to use a dependency injection tool like Unity, in order to provide to your plug-ins the configuration they required. By proceeding in this way, your plug-ins will no longer need to reference System.Configuration.dll.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM