我正在使用https://blog.falafel.com/working-system-runtime-caching-memorycache/
所述的缓存项目但是我需要开发这个类的一些实现,它们在ConsentDataContext项中使用不同的表。
此类是静态的,因此我需要将其更改为单例,然后从定义了GetItem和AddOrGetExisting方法的抽象继承。或者创建两个单独的类并使用反射来返回正确的实例。
解决这个问题的最佳方法是什么?
实施1
public static class Consent1Cache
{
private static MemoryCache _cache = new MemoryCache("ConsentType1Cache");
public static object GetItem(string key)
{
return AddOrGetExisting(key, () => InitItem(key));
}
private static T AddOrGetExisting<T>(string key, Func<T> valueFactory)
{
var newValue = new Lazy<T>(valueFactory);
var oldValue = _cache.AddOrGetExisting(key, newValue, new CacheItemPolicy()) as Lazy<T>;
try
{
return (oldValue ?? newValue).Value;
}
catch
{
// Handle cached lazy exception by evicting from cache.
_cache.Remove(key);
throw;
}
}
public static string InitItem(string consentNumber)
{
using (DLL.ConsentDataContext db = new DLL.ConsentDataContext())
{
return db.vw_ConsentType1.Where(x => x.ConsentNumber == consentNumber).Select(c => c.ConsentNumber + " - " + c.Proposal).FirstOrDefault();
};
}
}
实施2
public static class Consent2Cache
{
private static MemoryCache _cache = new MemoryCache("ConsentType2Cache");
public static object GetItem(string key)
{
return AddOrGetExisting(key, () => InitItem(key));
}
private static T AddOrGetExisting<T>(string key, Func<T> valueFactory)
{
var newValue = new Lazy<T>(valueFactory);
var oldValue = _cache.AddOrGetExisting(key, newValue, new CacheItemPolicy()) as Lazy<T>;
try
{
return (oldValue ?? newValue).Value;
}
catch
{
// Handle cached lazy exception by evicting from cache.
_cache.Remove(key);
throw;
}
}
public static string InitItem(string consentNumber)
{
using (DLL.ConsentDataContext db = new DLL.ConsentDataContext())
{
return db.vw_ConsentType2.Where(x => x.ConsentNumber == consentNumber).Select(c => c.ConsentNumber + " - " + c.Proposal).FirstOrDefault();
};
}
}