views:

62

answers:

2

For example, I created a provider service that uses a database. In web.config, how do I set the provider's connection string to the main application connection string, defined in <ConnectionStrings>?

A: 

You could create a custom config element that reads the configuration for main app config.

Don't take this line for line but something like...

public class ProviderConfiguration : ConfigurationSection
{
    #region Constructors
    public ProviderConfiguration () { }
    #endregion

    #region Public Properties
    [ConfigurationProperty("ProviderConnection")]
    public ProvderSettingsConfigElement ProvderConnection
    {
        get { return (ProvderSettingsConfigElement)this["ProviderConnection"]; }
    }

    #endregion
}

public class ProvderSettingsConfigElement : ConfigurationElement
{
    #region Constructors
    public ProvderSettingsConfigElement () { }

    public WebSecuritySettingsDataProviderElement(string name, string type)
    {
        ConnectionString = ConfigurationManager.Get("mainAppConnString");
    }

    #region Public Properties
    [ConfigurationProperty("connectionString")]
    public string ConnectionString{get; set;}

}
matt_dev
+1  A: 

Matt's answer is pretty much there, with a couple of tweaks.

If you're happy to have it outside of the configuration code itself, once you've picked up your provider configuration, you can just talk to the main connection strings section directly from your provider classes:

var provider = ConfigurationManager.GetSection("ProviderConfiguration")
                as ProdviderSettingsSection;

ConnectionString connStr = 
    WebConfigurationManager.ConnectionStrings[provider.ConnectionString];

If you want to wrap it all up in the provider you'll need a backing field for your properties:

public class ProvderSettingsConfigElement : ConfigurationElement {
  private m_ConnectionString;

  [ConfigurationProperty("connectionString")]
  public string ConnectionString{
    // Probably want to check m_ConnectionString for IsNullOrEmpty
    get{ return WebConfigurationManager.ConnectionStrings[m_ConnectionString]; } 
    set{ m_ConnectionString = value;}
  }
}
Zhaph - Ben Duguid