Pages

Thursday, December 11, 2008

ASP.NET Caching Part 2

Data Caching
So we know that we can cache an entire page, or a fragment of a page by caching down to the user control level. Wouldn’t it be great if we could cache down to the object level? The good news is you can with ASP.NET Data caching.

The cache consists of a dictionary collection that is private to each application in memory. To insert items in the cache simply provide the collection with a unique name:

Cache["USER_id"] = myObject;

Retrieving the object form the cache:

myObj = (MyObj)Cache["USER_id"];

It is a good time to point out that you should always remember to check for null, and be sure to caste to your datatype.

Cache Configuration
If you are familiar with how caching worked in ASP.NET 1.0, you realize that managing all the cache directions for all your pages could potentially get out of hand. ASP.NET 2.0 introduces Cache Profiles that helps you centrally manage your cache. Cache settings can be inherited by your pages, and overridden if required by using the OutputCache directive.

The page directive looks pretty much the same, expect this time it references a cache profile that you defined in your web.config file.

<%@ Page Language=”C#” %>
<%@ OutputCache CacheProfile=”testCacheProfile” VaryByParam=”none” %>













So each and every page that references the ‘testCacheProfile’ can be centrally managed in the web.config, this means that any changes to the cache settings in the web.config file will be automatically changed on all your referenced pages.

No comments: