您的位置:首页 > 其它

实战1.1下Web.Config配置标记configSections

2006-04-10 17:24 295 查看
genson

Microsoft ASP.NET 1.1
Microsoft Visual Studio2003
摘要:了解如何自定义一个新的Section

SDK描述:

您可以用自己的 XML 配置标记扩展标准的 ASP.NET 配置设置集。若要完成该操作,您必须创建自己的配置节处理程序。该处理程序必须是一个实现 IConfigurationSectionHandler 接口的 .NET Framework 类。节处理程序解释并处理 Web.config 文件特定部分中 XML 标记中定义的设置并根据配置设置返回适当的配置对象。处理程序类返回的配置对象可以是任何数据结构;它不限于任何基配置类或配置格式。
大体的意思是要我们写一个类并实现IConfigurationSectionHandler接口,IConfigurationSectionHandler接口只有一个方法

object Create(
object parent,
object configContext,
XmlNode section
);

程序大体功能。。通过Section配置节读取数据库连接串,把配置信息保存到Cache里面。再利用反射读取工厂模式的DataProvider

首先,我们先写一个读取Web.Config配置节的ProviderConfig类

using System;
using System.Xml ;
using System.Configuration ;
using System.Web ;
namespace RssLayer.Configuration

再次,我们写一个类实现IConfigurationSectionHandler接口类。

using System;
using System.Configuration ;
using System.Xml ;
namespace RssLayer.Configuration

最后,我们根据写好的程序去配置Web.Config

<configSections>
<sectionGroup name="RssConfig">
<section name="ProviderConfig" type="RssLayer.Configuration.ProviderConfigSectionHandler,RssLayer"></section>
</sectionGroup>
</configSections>

<RssConfig>
<ProviderConfig type="RssLayer.DataProvider.SqlDataProvider,RssLayer" connectionString="Server=rss;UID=sa;Pwd=123;DataBase=rsscn"></ProviderConfig>
</RssConfig>
最后我们数据抽象类DataProvider调用

using System;
using System.Data ;
using System.Web;
using System.Web.UI ;
using System.Web.Caching ;
using System.Reflection ;
using System.Collections.Specialized ;
using RssLayer.Object ;
using RssLayer.Configuration ;

namespace RssLayer.DataProvider
{
/**//// <summary>
/// RsscnProvider 的摘要说明。
/// </summary>
public abstract class RssDataProvider {

"Instance"#region"Instance"
/**//// <summary>
/// Instance
/// </summary>
public static RssDataProvider Instance
{
get
{
System.Web.Caching.Cache cache = HttpRuntime.Cache ;
if(cache["DataProvider"]==null)
{
ProviderConfig config = ProviderConfig.GetConfig();
string[] types = config.Type.Split(',');
AssemblyName name = new AssemblyName();
name.Name=types[1];
Assembly ass = Assembly.Load(name);
Type t = ass.GetType(types[0]);
//object obj = Activator.CreateInstance(t,new object[]{config.ConnectionString});
//Or
ConstructorInfo construct = t.GetConstructor(new Type[]{typeof(string)});
object obj = construct.Invoke(new object[]{config.ConnectionString});

cache["DataProvider"] = obj;
}

return (RssDataProvider)cache["DataProvider"];
}
}

#endregion
}
}
本人比较少写文章,有可能描述不清的,欢迎赐教与修正。如果管理员觉得不好的。可以撤销在首页。本程序在http://www.rsscn.net通过。

Msn:genson123@hotmail.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: