Donut caching used to cache an entire web page except for one or more small portion of the page. In other words, suppose we want to cache a maximum portion of the view except the minimum portion then we can finalize to use DonutCache. I know while start reading this, many questions will arise. Let us discuss this in “What is in Mind” section.
What is in Mind?
Q1 :At meantime, we think what will happen when we use Output Caching ? The output cache will cache the entire web page.
Q2 :However, what can we do when we want to do the inverse of the Donut Caching? we want to use Donut hole cache instead of the DonutCache to cache the small portion of the view instead of maximum portion (inverse of DonutCache)
When to use Donut Cache?
Let we assume, having a web site which contains the home page with displaying login user name (small portion will be in dynamic) , and the remaining are static content.
If you want to cache users by using OutputCache with VaryByParam User ID, then the entire page will be cached every time for each user with a different user name. This is a bad approach because if 5000 users logged into the site, then there will be 5000 pages have been cached.
Good Approach :
In this scenario, we can use DonutCaching. It is useful when page containing most of the information is rarely Changed and few items changing dynamically( based on the parameter).
Including MVCDonutCaching using NuGet Package:
We can install MVCDonutCaching using NuGet or using Package Manager Console Go to Tools -> Library Package Manager -> Package Manager Console, then type the command “Install-package MvcDonutCaching” in the console as shown below image.
Once we installed MvcDonutCaching package, we can add the DonutOutputCache attribute to the action or to the controller. Most of the parameter type of OutputCache attribute are also available in the DonutCache as shown below.
From the below code, the static content in the Index view has cached for 30 seconds for all users expect dynamic content which is specified inside the view(ie., loading partial view).
While running the application, when we browse DonutCache controller then it will load the index view. If we refresh the page before 30 seconds, then index view will not refresh because it has been cached by the DonutCache (Time remain the same in the view, but time from the partial view had been updated for every refresh as shown below) . But LoadUserDetail has been refreshed every time because it hasn’t caught in cache as show below.