This blog post is about fragment caching in EPiServer CMS. We take a look at how to use user control output caching together with the DataFactoryCache class in EPiServer.
Fragment caching
Fragment caching, also known as user control output caching, is used to cache portions of a page. This is especially useful if the website has dynamic content which can depend on a user’s current session and we don’t want to cache the entire output of a page.
DataFactoryCache
The DataFactoryCache class in EPiServer CMS is responsible for maintaining the cache for PageData-objects. Joel Abrahamsson has a good blog post which explains how EPiServer CMS works with the cache.
The DataFactoryCache class also supports creating CacheDependency-objects which are used to manage and invalidate other cached objects should a page in EPiServer CMS change.
Extending UserControlBase
PageBase implements the virtual method SetCachePolicy() which is called on OnInit(). This sets the cache policy for the entire page which you can configure in EPiServer.config. The entire page will be then added to the output cache.
To support fragment caching we add the virtual method SetCacheDependency() to our base class which inherits from UserControlBase. See code sample below.
public class AlloyTechUserControlBase : UserControlBase
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
SetCacheDependency();
}
/// <summary>
/// Sets a cache dependency to CurrentPage if the user control supports output cache
/// </summary>
public virtual void SetCacheDependency()
{
// Check if the user control supports caching
if (this.CachePolicy.SupportsCaching)
{
// Create a dependency to the page instance
this.CachePolicy.Dependency = DataFactoryCache.CreateDependency(this.CurrentPage.PageLink);
}
}
}
Any control that inherits from the base class AlloyTechUserControlBase will now call the SetCacheDependency() in its OnInit()-event. We enable output cache for a user control by adding the OutputCache-directive. See sample code below.
<%@ OutputCache Duration="1800" VaryByParam="id;epslanguage" %>
A cache dependency is created for any user control that inherits from the AlloTechUserControlBase and has the OutputCache-directive added. When the PageData-object changes the output cache for the user control is flushed.
Security
Be careful not to cache anything that could vary if an editor or administrator of the website is logged on. Should they be the first to visit the page, and the result is added to the cache, then all subsequent requests until the PageData-object changes will produce the same cached result.
Further reading
How EPiServer CMS caches PageData objects by Ted Nyberg
Cache objects in EPiServer with page dependencies by Joel Abrahamsson
The EPiServer CMS Output Cache Explained by Joel Abrahamsson
Customizing output cache variation by Magnus Paulsson
The Output Cache – When and Why by Daniel van den Tempel