Sunday, December 25, 2011

Simple cache provider

Instead of using the if condition to take the data from the or from the db on each data function, i have created a simple function that uses delegate and generics,
the function improve your code concentration and פrevents code replication
the function has 3 arguments:
- cacheKey - the key name to use in the cache object
- getfromDbFunc - this function will call in case that the cache is empty
- param - the parameter will be send to getfromDbFunc function


public class CacheProvider
{
public T GetData<T, P>(string cacheKey,
Func<P, T> getfromDbFunc, object param) where T : class
{
T item = HttpRuntime.Cache.Get(cacheKey) as T;
P p = (P)param;
if (item == null)
{
item = getfromDbFunc(p);
HttpContext.Current.Cache.Insert(cacheKey, item, null,
DateTime.UtcNow.AddMinutes(10),
System.Web.Caching.Cache.NoSlidingExpiration);
}
return item;
}
}


Example how to use:

protected void Page_Load(object sender, EventArgs e)
{
CacheProvider cacheProvider = new CacheProvider();
int userid = 17;
var user = cacheProvider.GetData<string, int>("user_" + userid, getUser, userid);
}
public string getUser(int id)
{
//TODO: retrieve user from db
return "newuser";
}
I'll be glad to get suggestions or improvements