in

ASPXWizard.net

.net and Ajax Community

Mina Labib

Extending Cache to Get Or Insert data

In current project I was planning to build caching functionality to keep some shared and not frequently changed data, I figured out that I will be using a lot of Cache[string Key], Cache.Get(), and/or Cache.Insert() methods. and that means I have to check if the data is in the cache already and if not I have to insert the data to the cache object.

I was thinking about having a method to check and update the cache without rewriting that over and over again, but that means I have to know what is the data type of the data needed to be stored, that brings us to Generics and Extensions to build extension methods to check the Cache object and get or insert data.

I am using ASP.NET MVC 1.0 in this project, below is the extension method to get or insert into Cache object:

using System;
using System.Web.Caching;

namespace CacheExtensions
{
    public static class CasheExtension
    {
        public static T GetOrInsert<T>(this Cache Cache, string key, Func<T> generator)
        {
            var result = Cache[key];
            if (result != null)
                return (T)result;
            result = (generator != null) ? generator() : default(T);
            Cache.Insert(key, result);
            return (T)result;
        }
    }
}

now you can consume it easily by calling the extended method as following:

object o = HttpRuntime.Cache.GetOrInsert<object>("key1",GenObj);

supposing GenObj is a pointer  to a method to generate an instance of type object.

Actually I used the same technique to get or add data to the session object too.

References: http://stackoverflow.com/questions/445050/how-can-i-cache-objects-in-asp-net-mvc

Comments

No Comments

Leave a Comment

(required)  
(optional)
(required)  
Add
ASPXWizard.net some rights reserved 2005-2007
Powered by Community Server (Non-Commercial Edition), by Telligent Systems