Age*_*ire 4 c# settings caching type-conversion asp.net-mvc-4
看,我正在开发一个MVC4项目的网站.该站点通常以非常简单的方式查询其数据库中的各种设置:
private static T GetSetting<T>(string parameterName)
{
return (T)Convert.ChangeType(/* bla bla SQL query code */, typeof(T));
}
Run Code Online (Sandbox Code Playgroud)
逻辑上的问题是 - 什么,你每次想要获得任何设置时都在查询数据库吗?如果你需要在一些for周期或东西中怎么办?
所以我想出了缓存解决方案,我需要知道我能做到最好.你怎么看?
internal static void ClearCache()
{
foreach (IDictionary cache in _caches)
cache.Clear();
}
private static readonly HashSet<IDictionary> _caches = new HashSet<IDictionary>();
private static class TypedCache<T>
{
private static readonly Dictionary<string, T> _cache = new Dictionary<string, T>();
internal static Dictionary<string, T> Cache { get { return _cache; } }
}
private static T GetSetting<T>(string parameterName)
{
T value;
if (!TypedCache<T>.Cache.TryGetValue(parameterName, out value))
{
_caches.Add(TypedCache<T>.Cache);
TypedCache<T>.Cache[parameterName] = value =
(T)Convert.ChangeType(/* bla bla SQL query code */, typeof(T));
}
return value;
}
Run Code Online (Sandbox Code Playgroud)
我听说IIS可以在内存中创建多个DLL副本(通过使用多个IIS进程).我怎么能强迫他只用一个呢?因此,整个我的想法都可以下地狱.
Convert仅当您想要更改值的类型时才应使用,例如。将字符串转换为数字,反之亦然。在您的情况下,值已经具有正确的类型(我假设),因此您只需要强制转换.
您不需要每种类型都有一个单独的字典,这不会给您带来任何好处。只需使用 single Dictionary<string, object>,然后将其强制转换(而不是Convert)到 T 中GetSetting<T>。