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

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

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)条件变为假。我在这里做错了什么?还是有其他方法可以缓存连接字符串。

wwjazrael 回答:如何缓存连接字符串并访问它?

我首先想到的是为什么要缓存它?它是配置数据,应足够快以在每次需要时获取。

如果您真的需要缓存,可以使用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");
本文链接:https://www.f2er.com/3062619.html

大家都在问