自定义web.config节处理程序

我之前设计了一个自定义部分处理程序,但我遇到了一个我似乎无法想到的问题。 我有一个像这样的配置部分:

  

我创建了以下处理程序类:

 using System.Configuration; namespace MyProject.Configuration { public class ProvidersSection : ConfigurationSection { public new Element this[string key] { get { } } } [ConfigurationCollection(typeof(ProviderElement))] public class ProvidersCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new ProviderElement(); } protected override object GetElementKey(ConfigurationElement element) { return element.ElementInformation.Properties["name"].Value; } public ProviderElement this[string key] { get { return (ProviderElement)base.BaseGet(key); } } } public class ProviderElement : ConfigurationElement { public string this[string name] { get { return string.Empty; } } } } 

为了成功执行以下代码,我需要在这些类中使用哪些代码?

 string query = ProvidersSection["tasks"].Queries["Insert"]; 

您应该考虑对要用作集合的Elements使用ConfigurationElementCollection和KeyValueConfigurationCollection 。 在这种情况下,您将必须创建元素集合,每个元素都具有KeyValueConfigurationCollection。 因此,您将拥有更多类似的内容,而不是您上面的XML配置:

     ...etc...    

您可以为每个“提供者”重复使用“queries”元素,它将是您的KeyValueConfigurationCollection。

谷歌快速搜索在MSDN上发表了这篇文章 ,这也可能有所帮助。

编辑 – 代码示例

您的根节定义将如下所示:

 public class ProviderConfiguration : ConfigurationSection { [ConfigurationProperty("Providers",IsRequired = true)] public ProviderElementCollection Providers { get{ return (ProviderElementCollection)this["Providers"]; } set{ this["Providers"] = value; } } } 

然后,您的Providers ElementCollection:

 public class ProviderCollection : ConfigurationElementCollection { public ProviderElement this[object elementKey] { get { return BaseGet(elementKey); } } public void Add(ProviderElement provider) { base.BaseAdd(provider); } public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMap; } } protected override ConfigurationElement CreateNewElement() { return new ProviderElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((ProviderElement)element).Key; } protected override string ElementName { get { return "Provider"; } } } 

然后,您的Provider元素:

 public class Provider : ConfigurationElement { [ConfigurationProperty("Key",IsRequired = true, IsKey = true)] public string Key { get { return (string) this["Key"]; } set { this["Key"] = value; } } [ConfigurationProperty("Queries", IsRequired = true)] public KeyValueConfigurationCollection Queries { get { return (KeyValueConfigurationCollection)this["Queries"]; } set { this["Queries"] = value; } } } 

您可能不得不使用KeyValueConfigurationCollection来使其正常工作,但我认为这将是一般的想法。 然后,当您在代码中访问此内容时,您将执行以下操作:

 var myConfig = (ProviderConfiguration)ConfigurationManager.GetSection("Providers"); //and to access a single value from, say, your products collection... var myValue = myConfig.Providers["Products"].Queries["KeyForKeyValuePairing"].Value; 

希望有所帮助。 现在就不要让我把它翻译成VB 😀