Selecting Cache Provider On the Fly in ASP.NET

By | March 19, 2011

If you have multiple Cache Provider in your ASP.NET application you can  set the output cache provider dynamically at runtime .  This is extremely useful if want to store cache data in different storage based on the usages of the data.

image

To use this features you need to override the GetOutputCacheProviderName() method within the Global.asax file of your web site. by default this return   base.GetOutputCacheProviderName(context) , where context is the current HTTPContext.

public override string GetOutputCacheProviderName(HttpContext context)
{
return base.GetOutputCacheProviderName(context);
}

Now if you want to change the cache provider just override the method and change provider name with some certain condition with respect to the current context.

public override string GetOutputCacheProviderName(HttpContext context)
{
if (context.Request.QueryString["MemberType"] == MemberType.Gold)
{
return "AspNetInternalProvider"

}
else
{
return base.GetOutputCacheProviderName(context);
}
}

Where base.GetOutputCacheProviderName(context) will return the cache provider name which has mentioned in webconig.

<caching>
<outputCache defaultProvider="AspNetInternalProvider">
<providers>
<add name="DiskCacheProvider"
type="CustomOutputCache.DiskCacheProvider, DiskCacheProvider"/>
</providers>
</outputCache>
</caching>