Search code examples
c#webformshashtableconnection-string

How to cache the connection string and access it?


I want to cache the connection string and used cached object throughout my project. I tried like below

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;
}

and accessing like this

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

but CachedObject.ContainsKey(key) condition getting false. What am I doing wrong here? or is there any other method to cache the connection string.


Solution

  • This should work (in a somewhat generic way):

    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;
        }
    }
    

    Anywhere you find appropriate in your code:

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