.net 自定义配置节点

在.net项目中, 可能有时候会遇到需要自定义配置节点,下面是自己在项目中用到的一个

1.配置定制类

-----全局配置

public class SubscribeTypeConfig : ConfigurationSection

    {
        [ConfigurationProperty("Name", DefaultValue = "SubscribeType", IsRequired = true, IsKey = false)]
        public String Name
        {
            get
            {
                return (string)this["Name"];
            }
            set
            {
                this["Name"] = value;
            }
        }

        [ConfigurationProperty("SubscribeTypeConfigs", IsDefaultCollection = false)]
        public SubscribeTypeConfigCollection SubscribeTypeConfigs
        {
            get
            {
                return (SubscribeTypeConfigCollection)this["SubscribeTypeConfigs"];
            }
        }

    }

---定义集合
    public class SubscribeTypeConfigCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new SubscribeTypeConfigElement();
        }
        protected override Object GetElementKey(ConfigurationElement element)
        {
            return ((SubscribeTypeConfigElement)element).Name;
        }
    }
---定义集合中的元素
    public class SubscribeTypeConfigElement : ConfigurationElement
    {
        [ConfigurationProperty("name", DefaultValue = "mail", IsRequired = true, IsKey = true)]
        public string Name
        {
            get
            {
                return (string)this["name"];
            }
            set
            {
                this["name"] = value;
            }
        }

    }

2.下面是在web.config中需要配置的

---configSections中的配置

 <section name="SendService" type="Songjiang.Platform.Subscribe.Common.SendServiceConfig,Songjiang.Platform.Subscribe.Common"/>
----具体配置节点
<SendService Name="SendService">
    <SendServiceConfigs>
      <add name="MailSend" ></add>
    </SendServiceConfigs>
  </SendService>

3.读取配置

 SendServiceConfig ssc = (SendServiceConfig)ConfigurationManager.GetSection("SendService");

 foreach (ServiceConfigElement sce in ssc.SendServiceConfigs)
                {
                    if (sce.SendTime == DateTime.Now.ToString("hh:mm"))
                    {
                      //etc..
                    }
                }


ps:这只是最简单的配置形式,还有其他的配置方式。写在这里 ,便于记忆。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值