Subscribe

RSS Feed (xml)

Using HttpContext for Per-Request Caching

Storing data within


HttpContext.Current.Items allows for data to exist for the duration


of the request and to be automatically discarded when the request is complete.


Public Function GetUserInfo(string username) As User


' Let's not go to the database each time we need the user's info


' the userKey is a unique value that identifies the user, such as the


' username


If (HttpContext.Current.Items(username) Is Nothing) Then


// Hang on to the data for this request only


HttpContext.Current.Items(username) = Provider.GetUserInfo(username);


End If


Return CType(HttpContext.Current.Items(username), User);


End Function


To see this code in action, see Users.cs class in the ASP.NET forums source code.


Comments


In some specialized cases, you want to cache some data only for the duration of the


request. A great example of this is in the ASP.NET forums (source code available at


www.asp.net).


The forums make use of personalization within each server control. A single page


may be composed of 10-12 server controls. Rather than each server control retrieving its


own set of data from the database, the code can reliably call the GetUserInfo() function


repeatedly. If the item is not found in the HttpContext.Items collection-a special dictionary


that exists for the duration of the request-it is created from the database and


added to HttpContext.Items.


This technique is very powerful because it allows your code to remain modular and


to take advantage of a caching technique to improve performance.

No comments:

Archives

Variety in the Web World