Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Using Cache Data Outside of Pages

I would like to create a data access layer to my application that gets data from Cache variables and sets teh Cache if it does not already exist. I figured the best way to make this reusable to all elements of my application was to include it in the App_Code folder as a custom class. I have methods that look like this:

public SiteInfo GetSiteInfo()
{
SiteInfo Source;
Source = (SiteInfo)Cache["SiteParams"];

if (Source == null)
{
Source = new SiteInfo(DomainName);
Cache["SiteParams"] = Source;
}

return Source;
}

For some reason it does not like for me to use this inside of a class. The compiler throws an error when I compile it. I then changed the class to extend the UserControl class:

public class DataStore : UserControl

It compiles when I do this, but I get the following runtime error:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

The same function works okay within a Page or UserControl on my site. How can I get a method like this one to work in a way that all pages can access it?

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
[1516 byte] By [hoyaabanks] at [2007-11-11 8:16:15]
# 1 Re: Using Cache Data Outside of Pages
The Page class has a property named Cache, so if you're in a class that inherits from Page, you can just say "Cache." If you're in a class that DOESN'T inherit from Page, you have to say, "HttpContext.Current.Cache."
Phil Weber at 2007-11-11 23:13:18 >