通过web.config迭代

时间:2013-06-20 11:52:38

标签: c# asp.net .net loops asp.net-web-api

我的web.config部分安排如下:

<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中复制很多代码,因为它们或多或少地执行相同的操作。 我有什么想法可以概括这个迭代?


编辑:通过创建对象列表来解决此问题。

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

然后迭代:

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

2 个答案:

答案 0 :(得分:1)

使用接口。如果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
    }
}

答案 1 :(得分:0)

您可以创建一个Configs集合:

[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 */