简体   繁体   English

在WCF中使用弱引用进行简单数据缓存

[英]Simple Data Caching using Weak References in WCF

Given that I have the following WCF service: 鉴于我有以下WCF服务:

class LookUpService
{
   public List<County> GetCounties(string state)
   {
       var db = new LookUpRepository();
       return db.GetCounties(state);
   }
}

class County
{
    public string StateCode{get;set;}
    public string CountyName{get;set;}
    public int CountyCode{get;set;}
}

What will be the most efficient (or best) way to cache a state's counties using weak references (or any other approach) so that we don't hit the database every time we need to look up data. 使用弱引用(或任何其他方法)缓存州县的最有效(或最佳)方法是什么,这样我们就不必每次需要查找数据时都访问数据库。

Note that we will not have access to the HttpRuntime (and HttpContext). 请注意 ,我们将无权访问HttpRuntime(和HttpContext)。

For this scenario you're going to want to use a WeakReference style hash table of sorts. 对于这种情况,您将要使用WeakReference样式的哈希表。 None is available in the BCL (until 4.0) but there are several available online. BCL中没有可用的功能(直到4.0),但在线有多个可用的功能。 I will be using the following for this sample 我将在此示例中使用以下内容

Try the following cdoe 尝试以下cdoe

class LookupService {
  private WeakHashtable<string,List<Count>> _map = new WeakHashtable<string,List<County>>();
  public List<County> GetCounties(string state) {
    List<Count> found;
    if ( !_map.TryGetValue(state, out found)) { 
      var db = new LookUpRepository();
      found = db.GetCounties(state);
      _map.Add(state,found);
    }
    return found;
  }
}

As you can see, it's not much different than using a normal Dictionary<TKey,TValue> 如您所见,与使用普通Dictionary<TKey,TValue>并没有太大区别

Why do you not have acccess to HttpRuntime? 为什么没有访问HttpRuntime的权限? You don't need the context. 您不需要上下文。 You only need the class. 您只需要上课。

You can use System.Web.Caching in a non-ASP.NET app, without using the HttpContext. 您可以在非ASP.NET应用程序中使用System.Web.Caching ,而无需使用HttpContext。

see also Caching in WCF? 另请参阅在WCF中缓存?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM