Server side caching

janjongboom edited this page Aug 8, 2011 · 2 revisions

Moth contains a sophisticated caching system, that is the only system to add support for 'Donut Caching' (output cache substitution) to ASP.NET MVC.

Donut caching?

This caching strategy is very awesome, because instead of choosing which parts of a page should be cached, you now specify which parts shouldn't be cached. This means: just mark every part of the page that is f.e. user specific, and only that part will be rendered again when the next user visits your site. Scott Guthrie explained it all in this blogpost, but killed the feature anyway in ASP.NET MVC.

Enabling it

First of all, you'll need to enable Moth's output caching feature in your Controller. Add the following attribute to your controller class:

[MothAction(OutputCaching = true)]
public class YourController : Controller

All requests will now be cached for 10 minutes, and you'll notice a way faster web page.

Excluding parts of the page

Moth can only do Output Cache Substitution on seperate Actions called by Html.RenderAction, so you'll have to move your user/profile dependent code into seperate actions. An example action is:

public ActionResult CurrentDateTime {
    return Content(DateTime.Now.ToString());
}

Normally, you would call this action in your view like:

<% Html.RenderAction("CurrentDateTime", "YourController"); %>

When enabling Moth's output caching, you'll notice that the date won't change when you refresh the page. Voila, the caching is working. To render this action as a 'donut hole' that is executed every time the page is rendered, change the code in the view to:

<p>Normal: <% Html.RenderAction("CurrentDateTime", "YourController"); %></p>
<p>Donut hole: <% Html.RenderMothAction("CurrentDateTime", "YourController"); %></p>

When you now render the page, you will notice that the page will only update the second item!