Channels ▼
RSS

.NET

Creating a Custom Output Cache Provider in ASP.NET 4


Configuring the Custom Cache Provider

To configure the custom cache provider, specify the details in your application's Web.config file. Here's how you can specify the configuration:

<configuration>
   <system.web>
      <compilation debug="true" targetFramework="4.0"/>
      <caching>
         <outputCache defaultProvider="CustomOutputCache">
            <providers>
               <add name="CacheProviderName" 
                    type="CacheProviderCategory"/>
            </providers>
         </outputCache>
      </caching>
   </system.web>
</configuration>

So, if you have implemented a custom cache provider called FileCacheProvider, for example, you can specify this in the application's configuration file:

<configuration>
  <system.web>
    <caching>
      <outputCache defaultProvider="AspNetInternalProvider">
        <providers>
          <add name="FileCache" 
           type="CustomCacheProvider"/>        
        </providers>
      </outputCache>
    </caching>
  </system.web>
</configuration>

Selecting the Custom Output Cache Provider Dynamically

Next, override the virtual method called GetOutputCacheProviderName() of the HttpApplication class in the global.asax file to ensure that the correct cache provider is selected at the application level.

public class Global : System.Web.HttpApplication
{
  public override string GetOutputCacheProviderName(HttpContext context)
  {
      return base.GetOutputCacheProviderName(context);
  }
}

It is also possible to select the output cache provider to be dynamically on a per-request basis by overriding the GetOutputCacheProviderName() method as shown in the code snippet below:

public class Global : System.Web.HttpApplication
{
  public override string GetOutputCacheProviderName(HttpContext context)
  {
      if(context.Request.Path.EndsWith("Default.aspx"))
          return "AspNetInternalProvider";

      return base.GetOutputCacheProviderName(context);
  }
}

Now, your Global.ascx.cs file should look similar to this:

using System;
using System.Web;

namespace DDJ
{
    public class Global : System.Web.HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {

        }

        void Application_End(object sender, EventArgs e)
        {

        }

        void Application_Error(object sender, EventArgs e)
        {

        }

        void Session_Start(object sender, EventArgs e)
        {

        }

        void Session_End(object sender, EventArgs e)
        {
            
        }

        public override string GetOutputCacheProviderName(HttpContext context)
        {
            if (context.Request.Path.EndsWith("Default.aspx"))
                return "AspNetInternalProvider";

            return base.GetOutputCacheProviderName(context);
        }
    }
}

Note that the Application_Start(), Application_End(), Application_Error(), Session_Start(), and Session_End() are the default event handlers of the System.Web.Global class. You can also make use of the RawUrl property of the Request object to get the right custom cache provider dynamically as shown here:

{
    if (context.Request.RawUrl.ToUpper().Contains("File"))
    {
        return "CustomFileOutputCacheProvider";
    }

    return base.GetOutputCacheProviderName(context);
 }

And, you are done! You can now use your custom cache provider in your application.

Conclusion

Caching can significantly reduce network latency and boost an application's performance. If you have a large number of concurrent requests to the same resource, caching can come in handy by allowing you to avoid redundant calls to the data stores. In this article, I explored the new features in the Cache API in .NET Framework 4, the ASP.NET Cache extensibility feature, and how these can be leveraged to implement your own custom cache provider.

References

These links provide additional information that you'll find helpful:

Extending ASP.NET Output Caching

Building and Using Custom OutputCache Providers in ASP.NET

Cache Abstraction on ASP.NET


— Joydip Kanjilal is a frequent author on Microsoft technologies. He has won the Microsoft MVP Award for the last five years.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video