KnowDotNet

Using ASP.NET Data Caching in a DLL (Outside of Page/CodeBehind)

Use HTTPContext To Access Cache Object in Data Access Layer

by Les Smith

How do I access the ASP.NET Cache Object from a Data Access Layer DLL called from an ASP.NET Page?  Almost every article you find on Google shows usage of the ASP.NET Cache object being referenced in the page or in CodeBehind.  However, in an application that I am working on, I need to reference the Cache object in a Data Access Layer (DAL).  I tried unsuccessfully to access the object in the code shown in Figure 1.

Figure 1 - What Does Not Work.

   using System.Web.Caching;

  
Cache cache = new Cache();
   cache[
"States"] = "my cached value";

This inevitably raised a NullReferenceException regardless of how I tried to use the cache object.  The troubling aspect was that every example I found searching the Web showed the following code.

Figure 2 - Code Working in ASP.NET Page or CodeBehind File.

   Cache["States"] = "my cached value";

With all of my stumbling about, using the System.Web.Caching NameSpace, there was no way for me to get the line of code shown in Figure 2 above to even compile.  I finally found that if I simply use the System.Web Namespace and HTTPContext, the following line of code works fine.

   HttpContext.Current.Cache["States"] = "my cached object";

The whole problem is that Caching is an ASP.NET functionality and works fine as shown in Figure 2 above as long as you put the code in ASP.NET context (i.e. Page/CodeBehind).  However, if you move it to a standalone DLL such as a Data Access Layer component, it no longer works.  Simply adding the "
HttpContext.Current." prefix to the Cache object puts your code in the proper context.  Ahh, the little things in life can be very frustrating.


Need to automatically organize your code windows?  You'll be amazed how easy it is to keep the code in your code windows organized.  TRY IT FREE FOR 30 DAYS BY CLICKING HERE.



Automatically generate braces in C#! Try CSharpCompleter and stop wasting valuable time needlessly typing hundreds of braces {} daily.  Try CSharpCompleter for 30 DAYS FREE.



Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog.
  

You can also email me directly at les@KnowDotNet.com.