Config Files and Dlls.

Well – A request recently came up on CodeProject asking how to associate a config file with a DLL and then use that configuration file. Like me you would think that this would be an easy thing to do, and that it would be taken care of for you automatically. Unfortunately, it would seem that this isn’t the case – it’s easy enough to do, but you have to do it yourself. One way to do it would be to use XML to read the configuration file directly and then deal with it from there, but it turns out that there is another way that allows you to use the ConfigurationManager directly. To do this, you need to load the application into a separate application domain and then use remoting to access it. This does give you the ability to load plugins with their own config file and isolate them from the main process just in case they are a bit naughty.

Here’s a quick overview of the process – suppose you have a config file for your plugin Dll that contains the following settings:

<appSettings>
  <add key="PluginName" value="My Funky Plugin" />
  <add key="RequiredVersion" value="2.1" />
<appSettings>

Your Dll class may implement the following interface:

public interface IPluginConfiguration
{
  string PluginName { get ; }
  string RequiredVersion { get ; }
} 
public class MyPlugin : IPluginConfiguration
{
  public string PluginName
  {
    get
    {
      return ConfigurationManager.AppSettings["PluginName"];
    }
  }
  public string RequiredVersion
  {
    get
    {
      return ConfigurationManager.AppSettings["RequiredVersion"];
    }
  }
}

Now, in your calling application you could do the following:

private IPluginConfiguration _config;
public void ActivatePlugin(string configFile, string domainName)
{ 
  AppDomainSetup setup = new AppDomainSetup(); 
  setup.ConfigurationFile = configFile; 
  AppDomain domain = AppDomain.CreateDomain(domainName, null, setup); 
 
  _config = (IPluginConfiguration)domain.CreateInstanceAndUnwrap("MyDll", "MyDll.MyDllClass");
  Console.WriteLine("Name {0}", _config.PluginName);
}

There you go – you can now refer to the localised config file. It’s that simple.

Advertisements

One thought on “Config Files and Dlls.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s