In C#, is it possible to decorate a method with an annotation to populate the cache object with the return value of the method?
Currently I'm using the following class to cache data objects:
public class SiteCache
{
// 7 days + 6 hours (offset to avoid repeats peak time)
private const int KeepForHours = 174;
public static void Set(string cacheKey, Object o)
{
if (o != null)
HttpContext.Current.Cache.Insert(cacheKey, o, null, DateTime.Now.AddHours(KeepForHours), TimeSpan.Zero);
}
public static object Get(string cacheKey)
{
return HttpContext.Current.Cache[cacheKey];
}
public static void Clear(string sKey)
{
HttpContext.Current.Cache.Remove(sKey);
}
public static void Clear()
{
foreach (DictionaryEntry item in HttpContext.Current.Cache)
{
Clear(item.Key.ToString());
}
}
}
In methods I want to cache I do this:
[DataObjectMethod(DataObjectMethodType.Select)]
public static SiteSettingsInfo SiteSettings_SelectOne_Name(string Name)
{
var ck = string.Format("SiteSettings_SelectOne_Name-Name_{0}-", Name.ToLower());
var dt = (DataTable)SiteCache.Get(ck);
if (dt == null)
{
dt = new DataTable();
dt.Load(ModelProvider.SiteSettings_SelectOne_Name(Name));
SiteCache.Set(ck, dt);
}
var info = new SiteSettingsInfo();
foreach (DataRowView dr in dt.DefaultView)
info = SiteSettingsInfo_Load(dr);
return info;
}
Is it possible to separate those concerns like so: (notice the new annotation)
[CacheReturnValue]
[DataObjectMethod(DataObjectMethodType.Select)]
public static SiteSettingsInfo SiteSettings_SelectOne_Name(string Name)
{
var dt = new DataTable();
dt.Load(ModelProvider.SiteSettings_SelectOne_Name(Name));
var info = new SiteSettingsInfo();
foreach (DataRowView dr in dt.DefaultView)
info = SiteSettingsInfo_Load(dr);
return info;
}