EPiServer CMS Fragment Caching
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, 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.
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.
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)
/// Sets a cache dependency to CurrentPage if the user control supports output cache
public virtual void SetCacheDependency()
// Check if the user control supports caching
// 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.
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.