views:

186

answers:

1

I am checking out the OutputCacheProvider in ASP.NET 4.0 and using it to store my output cache into the MongoDb database. I am not able to understand the purpose of Add method which is one of the override methods for OutputCacheProvider. The Add method is invoked when you have VaryByParam set to something. So, if I have VaryByParam = "id" then the Add method will be invoked.

But after the Add the Set is also invoked and I can insert into the MongoDb database inside the Set method.

public override void Set(string key, object entry, DateTime utcExpiry)
{
    // if there is something in the query use the path and query to generate the key 
    var url = HttpContext.Current.Request.Url;

    if (!String.IsNullOrEmpty(url.Query))
    {
        key = url.PathAndQuery;
    }

    Debug.WriteLine("Set(" + key + "," + entry + "," + utcExpiry + ")");  
    _service.Set(
        new CacheItem() { Key = MD5(key), Item = entry, Expires = utcExpiry }
    ); 
}

Inside the Set method I use the PathAndQuery to get the params of the QueryString and then do a MD5 on the key and save it into the MongoDb database.

It seems like the Add method will be useful if I am doing something like VaryByParam = "custom" or something.

Can anyone shed some light on the Add method of OutputCacheProvider?

+5  A: 

They are similar, but there is a slight difference. Looking at the MSDN documentation for the OutputCacheProvider class

  • Set - "Inserts the specified entry into the output cache, overwriting the entry if it is already cached"
  • Add - "Inserts the specified entry into the output cache."

The remarks for "Add" go on to say

"If there is already a value in the cache for the specified key, the provider must return that value. The provider must not store the data passed by using the Add method parameters. The Add method stores the data if it is not already in the cache. If the data is in the cache, the Add method returns it"

So for new values that aren't already in the cache they will behave identically, but where the value already exists, Set updates it, whereas Add leaves the original value intact.

David Gardiner