如何缓存连接字符串并访问它?

How to cache the connection string and access it?

我想在整个项目中缓存连接字符串和使用的缓存对象。我试过如下

public static void Demo()
{
Hashtable Hashtable = new Hashtable()
Hashtable.Add("WEBConnectionString", ConfigurationManager.ConnectionStrings["WEBConnectionString"].ConnectionString);
HttpContext.Current.Application["CachedValue"] = Hashtable;}

public static string Method(string key)
{
  string result = string.Empty;
  Hashtable CachedObject = (Hashtable)HttpContext.Current.Application["CachedValue"];
  if (CachedObject != null && CachedObject.ContainsKey(key))
   { 
      result = CachedObject[key].ToString();
   }
return result;
}

并像这样访问

string conString = Utility.Method("WEBConnectionString");

CachedObject.ContainsKey(key) 条件变得错误。我在这里做错了什么?或者是否有任何其他方法来缓存连接字符串。

我的第一个想法是为什么要缓存它?它是配置数据,应该足够快,可以在您每次需要时获取。

如果您真的需要缓存,HttpContext.Current.Application 有更现代的替代方法。

您可以按照评论中的建议使用 IOC 容器并将其配置为单例。不过,为此目的设置 IOC 容器似乎有点过分了。如果您有多个服务器并且想确保它们具有相同的状态,请考虑使用像 Redis 这样的分布式缓存。

其他替代方法是将连接字符串存储在静态变量中,使用 MemoryCache、HttpRuntime.Cache 或 HttpContext.Current.Cache。

使用惰性静态变量的示例:

private static Lazy<string> ConnectionString = new Lazy<string>(() => ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString);

// Access the connection string: var connectionString = ConnectionString.Value;

这应该有效(以某种通用的方式):

public class HttpContextCache
{
    public void Remove(string key)
    {
        HttpContext.Current.Cache.Remove(key);
    }

    public void Store(string key, object data)
    {
        HttpContext.Current.Cache.Insert(key, data);
    }

    public T Retrieve<T>(string key)
    {
        T itemStored = (T)HttpContext.Current.Cache.Get(key);
        if (itemStored == null)
        {
            itemStored = default(T);
        }

        return itemStored;
    }
}

代码中任何您认为合适的地方:

// cache the connection string
HttpContextCache cache = new HttpContextCache();
cache.Store("WEBConnectionString", ConfigurationManager.ConnectionStrings["WEBConnectionString"].ConnectionString);

// ...

// get connection string from the cache
HttpContextCache cache = new HttpContextCache();
string conString = cache.Retrieve<string>("WEBConnectionString");