开发者

Simple Data Caching using Weak References in WCF

开发者 https://www.devze.com 2022-12-26 01:39 出处:网络
Given that I have the following WCF service: class LookUpService { public List<County> GetCounties(string state)

Given that I have the following WCF service:

class LookUpService
{
   public List<County> GetCounties(string state)
   {
       var db = new LookUpReposito开发者_开发知识库ry();
       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).


For this scenario you're going to want to use a WeakReference style hash table of sorts. None is available in the BCL (until 4.0) but there are several available online. I will be using the following for this sample

  • http://blogs.msdn.com/jaredpar/archive/2009/03/03/building-a-weakreference-hashtable.aspx

Try the following 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>


Why do you not have acccess to 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.

see also Caching in WCF?

0

精彩评论

暂无评论...
验证码 换一张
取 消