Iterate through web.config

本文关键字:config web through Iterate | 更新日期: 2023-09-27 18:19:24

我有网页。配置段安排如下:

<Section>
  <service1>
    <add name="Web" info="xyz"/>     
  </service1>
  <service2>
    <add name="App" info="xyz"/>     
  </service2>
  <service3>
    <add name="Data" info="xyz"/>     
  </service3>  
</Section>

我用

遍历了每个元素
var mySection = (Sections)ConfigurationManager.GetSection("Section");

foreach (SectionsElement element in mySection.service1)
foreach (SectionsElement element in mySection.service2)
foreach (SectionsElement element in mySection.service3)

然而,这需要在每个foreach中复制大量代码,因为它们或多或少执行相同的事情。有什么想法可以概括这个迭代吗?


Edit:通过创建一个对象列表来解决这个问题。

var allservices = new List<object>(){
  mySection.service1,
  mySection.service2,
  mySection.service3
}

然后迭代:

foreach (IEnumerable service in allservices)
  {
    foreach (SectionsElement element in service)
    {
      //repetitive code
    }
  }

Iterate through web.config

使用接口。如果mySection.service1, .service2.service3实现相同的接口,例如IMyService,您可以轻松地这样做:

var services = new IMyService[] 
{ 
    mySection.service1, 
    mySection.service2, 
    mySection.service3 
};
foreach (var service in services)
{
    foreach (SectionsElement element in service)
    {
        // repetitive code
    }
}

您可以直接创建一个配置集合:

[ConfigurationProperty("Service", IsRequired = true)]
public string Service
 {
 ...
 }

public class ServiceConfigCollection : ConfigurationElementCollection
{
    public ServiceConfig this[int index]
    {
        get
        {
            return base.BaseGet(index) as ServiceConfig;
        }
        set
        {
            if (base.BaseGet(index) != null)
            {
                base.BaseRemoveAt(index);
            }
            this.BaseAdd(index, value);
        }
    }

    protected override System.Configuration.ConfigurationElement CreateNewElement()
    {
        return new ServiceConfig();
    }
    protected override object GetElementKey(System.Configuration.ConfigurationElement element)
    {
        return ((ServiceConfig)element).Service;
    }
}
public class ServiceConfigSection : ConfigurationSection
{
    [ConfigurationProperty("Entries", IsDefaultCollection = false)]
    [ConfigurationCollection(typeof(ServiceConfigCollection),
        AddItemName = "add",
        ClearItemsName = "clear",
        RemoveItemName = "remove")]
    public ServiceConfigCollection Entries
    {
        get
        {
            return (ServiceConfigCollection)base["Entries"];
        }
    }
}

在配置文件中给出:

<configSections>
  <section
    name="Services"
    type="xxx.classes.ServiceConfigSection, xxx"
    allowLocation="true"
    allowDefinition="Everywhere"
  />
</configSections>
<Services>
  <Entries>
    <add .../>
    <add .../>
  </Entries>
</Services>

然后在代码中:

var section = ConfigurationManager.GetSection("Services") as ServiceConfigSection;
/* do something with section.Entries */