SoxFan44
SoxFan44

Reputation: 147

Load database connection strings from another file

I have a web application that has a Web.config file, but I need it to load several sections from another config file that's located in a defined location (not my design!). One of these sections is connectionStrings. I've tried the following, but I get an error when my web service loads saying System.InvalidOperationException: No connection string named 'MyDataModel' could be found in the application config file.

ConfigurationFileMap map = new ConfigurationFileMap(@"C:\conf1.conf");
config = ConfigurationManager.OpenMappedMachineConfiguration(map);

ConfigurationManager.RefreshSection("connectionStrings");

Here is the relevant part of my config file:

    <configSections>
    <section name="connectionStrings" type="System.Configuration.ConnectionStringsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" requirePermission="false"/>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="MyDataModel" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;
      ..."/>
  </connectionStrings>

I'm aware that I can "include" a config file snippet in another config file, but that won't work here because the file that would be included contains several other sections. Is there a way that I can get the runtime to properly load my external config file? Thanks!

Upvotes: 3

Views: 1815

Answers (1)

Bill Sambrone
Bill Sambrone

Reputation: 4454

You are on the right track with using the ConfigurationManager to read a mapped config. The next bit is that you have to manually grab the keys when you want them. Here is a very similar question where the answer addresses the manual reading of the stuff you want:

Equivalent to 'app.config' for a library (DLL)

Copied from the above link:

string GetAppSetting(Configuration config, string key)
{
    KeyValueConfigurationElement element = config.AppSettings.Settings[key];
    if (element != null)
    {
        string value = element.Value;
        if (!string.IsNullOrEmpty(value))
            return value;
    }
    return string.Empty;
}

EDIT:

Since EF only looks at your local config (AFAIK), what about generating your web.config using a T4 template? You can then pipe in the necessary data from the remote config file. I found a good article on how to do this:

http://www.geoffhudik.com/tech/2010/10/19/webconfig-automation-with-t4-and-a-macro.html

EDIT2:

Is using metadata in your EF connection string an option? If so, you can point it at that other assembly without having to mess with ConfigurationManager:

http://msdn.microsoft.com/en-us/library/vstudio/cc716756(v=vs.100).aspx

Upvotes: 1

Related Questions