用System.Web.Caching.Cache保存数据类的缓存

本文介绍了一种通过使用缓存来减少数据提供者实例化开销的方法。该方法首先从配置文件中读取指定的数据提供者类名和所在程序集路径,并利用反射加载类的构造函数。为了提高性能,会将加载过程的结果存储在缓存中避免重复加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

/// The DataProvider class contains a single method, Instance(), which returns an instance of the  /// user-specified data provider class.  ///  public class DataProvider  {   public static IDataProvider Instance()   {    //use the cache because the reflection used later is expensive    Cache cache = System.Web.HttpContext.Current.Cache;

   if ( cache["IDataProvider"] == null )    {     //get the assembly path and class name from web.config     String prefix = "";     NameValueCollection context =

(NameValueCollection)ConfigurationSettings.GetConfig("appSettings");     if (context == null)     {      //can not get settings      return null;     }

    String assemblyPath = context[prefix +

"DataProviderAssemblyPath"];     String className = context[prefix +

"DataProviderClassName"];

    // assemblyPath presented in virtual form, must convert to

physical path     assemblyPath =

HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath + "/bin/" +

assemblyPath);     

    // Uuse reflection to store the constructor of the class

that implements IWebForumDataProvider     try     {      cache.Insert( "IDataProvider", Assembly.LoadFrom(

assemblyPath).GetType( className ).GetConstructor(new Type[0]), new CacheDependency(

assemblyPath ) );     }     catch (Exception)     {

     // could not locate DLL file      HttpContext.Current.Response.Write("<b>ERROR:</b>

Could not locate file: <code>" + assemblyPath + "</code> or could not locate class <code>" +

className + "</code> in file.");      HttpContext.Current.Response.End();     }    }    return (IDataProvider)( 

((ConstructorInfo)cache["IDataProvider"]).Invoke(null) );   }  }

 

相关文章
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值