Asp.NET Caching

I’ve implemented caching on a file (XML) which gets sent to the graphs controls to render it.
However, I was told to implement caching in a way that can be easily switched on and off (meaning setting a value in web.config).

Is there a way I can turn caching on and off depending on a value in a web.config file? Thank you lots!

@oded the code you supplied doesn’t fit in my scenario because I’d have to rewrite existing code for instance:

if(bool.parse(confi.... == "true"){
 if(Cache[x] == null){
  load the XML document and insert it into the Cache object }
 else{
 get the xml document from the Cache object. } } 

else repeat myself by reloading the document from object.

I’m sure there’s got to be a better solution to this.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Just check for a value of a key in the config file.

In appSettings section:

<add key="cacheXML" value="true" />

And in your code check this:

if(bool.Parse(ConfigurationManager.AppSettings["cacheXML"]))
{
  // use caching
}

Note: this will throw an exception if the key does not exist in the app settings.

Note2: You should abstract away the dependency on configuration, so you can test your code without needed a config file.

Solution 2

There is a documented way of creating caching profiles here – when your web.config contains the cache profiles you need, then make your pages use the profile by supplying the cacheprofile name to the @outputcache directive in the relevant pages.

Solution 3

You could add an caching aspect to your business layer.

But that depends on how you implemented your business logic? Do you have a separate business layer and some kind of dependency injection (like Ninject) in place?

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply