Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 476
g t Avatar asked Sep 06 '25 08:09

g t


2 Answers

By default the ConfigurationManager loads the .config for the entry assembly, i.e. 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.

like image 90
Stefán Jökull Sigurðarson Avatar answered Sep 08 '25 20:09

Stefán Jökull Sigurðarson


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.

like image 31
schglurps Avatar answered Sep 08 '25 19:09

schglurps