Selecting Cache Provider On the Fly in ASP.NET

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>
Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.