【问题标题】:How to cache the connection string and access it?如何缓存连接字符串并访问它?
【发布时间】:2020-03-16 16:11:56
【问题描述】:

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

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

【问题讨论】:

  • 这是一个什么样的网络应用程序? MVC?网络表单?
  • 嗯,您可以使用 IOC 容器和 DI,并让软件自动提供数据库上下文的实例 - 但我更好奇为什么您看不到连接的当前位置字符串喜欢(配置文件/配置管理器)作为整个项目都可用的缓存?
  • @mason Web 表单
  • 你为什么不直接访问ConfigurationManager 并跳过缓存?
  • @Train 这就是要求。我必须

标签: c# webforms hashtable connection-string


【解决方案1】:

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

如果你真的需要缓存,还有更现代的替代 HttpContext.Current.Application。

您可以使用 cmets 中建议的 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;

【讨论】:

    【解决方案2】:

    这应该可以工作(以某种通用的方式):

    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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      • 2011-07-10
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 2011-05-11
      相关资源
      最近更新 更多