Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Access cache from class file 2

Status
Not open for further replies.

jondow

Programmer
Oct 19, 2006
45
GB
Hi All,

I have a asp.net code behind page (2.0 vb.net) which adds to the cache in the the format
System.Web.Caching.Cache.Add("mycache",.......

I want to be able to access the cache from a separate class file like so
Dim c = System.Web.Caching.Cache("mycache")

but get the error "Cache is a type in caching and cannot be used as an expression".

Can someone please explain this and if possible provide an alternative approach?

Many thanks!

Rick
 
while this does work I find 2 problems with it.
1. the class now depends on the the web context.
2. you cannot test this code in isolation.

another option is to use an adapter to adapter the http cache to a generic cache. You can also get some type casting as well.

Code:
interface ICache
{
   void put<T>(string key, T item);
   T get<T>(string key);
}

class HttpCacheAdapter ICache
{
   public void put<T>(string key, T item)
   {
       HttpContext.Current.Cache[key] = item;
   }

   public T get<T>(string key)
   {
       return (T) HttpContext.Current.Cache[key];
   }
}
then it can be used this way
Code:
class Service
{
   private readonly ICache cache;

   public Service(ICache cache)
   {
       this.cache = cache;
   }

   public void do_something()
   {
       cache.put("one", 1);
       var i = cache.get<int>(one);
   }
}
this is the simplest implementation. you could also add a specification to determine how the cache should expire.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top