views:

116

answers:

2

Given that I have the following WCF service:

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).

+1  A: 

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

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>

JaredPar
A: 

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 http://stackoverflow.com/questions/922116/caching-in-wcf/922194#922194

Cheeso