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

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

FasttrainThe 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.

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.

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

daniel
daniel
Developer
Recent Posts
Contact Us

We're not around right now. But you can send us an email and we'll get back to you, asap.

Not readable? Change text. captcha txt

Start typing and press Enter to search