1

鉴于我有以下 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;}
}

使用弱引用(或任何其他方法)缓存州县的最有效(或最佳)方法是什么,这样我们就不会在每次需要查找数据时都访问数据库。

请注意,我们将无法访问 HttpRuntime(和 HttpContext)。

4

2 回答 2

1

对于这种情况,您将需要使用WeakReference各种样式哈希表。BCL 中没有可用的(直到 4.0),但有几个在线可用。我将为此示例使用以下内容

试试下面的 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;
  }
}

如您所见,它与使用普通的没有太大区别Dictionary<TKey,TValue>

于 2010-04-02T17:50:25.170 回答
0

为什么您无法访问 HttpRuntime?你不需要上下文。你只需要上课。

您可以在非 ASP.NET 应用程序中使用 System.Web.Caching ,而无需使用 HttpContext。

另请参阅WCF 中的缓存?

于 2010-04-02T17:53:38.000 回答