Zum Beispiel habe ich einen Provider-Service erstellt, der eine Datenbank verwendet. Wie setze ich in web.config die Verbindungszeichenfolge des Anbieters auf die Hauptanwendungsverbindungszeichenfolge, die in < ConnectionStrings> definiert ist?Wie referenziere ich die Werte von Konfigurationselementen in anderen Konfigurationselementen?
2
A
Antwort
1
Matt ‚s Antwort ziemlich es ist, mit ein paar Verbesserungen.
Wenn Sie glücklich sind, es sich außerhalb des Konfigurationscodes zu haben, sobald Sie Ihren Provider-Konfiguration ausgewählt haben, können Sie auf die Hauptverbindungszeichen Abschnitt sprechen nur direkt von Ihrem Provider-Klassen:
var provider = ConfigurationManager.GetSection("ProviderConfiguration")
as ProdviderSettingsSection;
ConnectionString connStr =
WebConfigurationManager.ConnectionStrings[provider.ConnectionString];
Wenn Sie alles in den Anbieter einbinden möchten, benötigen Sie ein Hintergrundfeld für Ihre Eigenschaften:
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;}
}
}
1
Sie könnten ein benutzerdefiniertes Konfigurationselement erstellen, das die Konfiguration für die Haupt-App-Konfiguration liest.
Nehmen Sie diese Linie nicht für Linie, sondern so etwas wie ...
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;}
}