Whereas the Cache API is designed to cache data for a long
period or until some condition is met, per-request caching simply means caching
the data for the duration of the request. A particular code path is accessed
frequently on each request but the data only needs to be fetched, applied,
modified, or updated once. This sounds fairly theoretical, so let us consider a
concrete example.
In the Forums application of Community Server, each server control used on a
page requires personalization data to determine which skin to use, the style
sheet to use, as well as other personalization data. Some of this data can be
cached for a long period of time, but some data, such as the skin to use for
the controls, is fetched once on each request and reused multiple times during
the execution of the request.
To accomplish per-request caching, use the ASP.NET
HttpContext. An instance of HttpContext is created with every request and is
accessible anywhere during that request from the HttpContext.Current property.
The HttpContext class has a special Items collection property; objects and data
added to this Items collection are cached only for the duration of the request.
Just as you can use the Cache to store frequently accessed data, you can use
HttpContext.Items to store data that you will use only on a per-request basis.
The logic behind this is simple: data is added to the HttpContext.Items
collection when it does not exist, and on subsequent lookups the data found in
HttpContext.Items is simply returned.