Casey Daly
Casey Daly

Reputation: 433

SQL Server data caching in ASP.NET

I am trying to use caching to save time refreshing my web application and do so automatically whenever the database changes, and am having trouble setting up the cache.

I have added the following code to where I access SQL...

SqlDependency.Start("Data Source=" + serverName + ";" + 
                    "Initial Catalog=...;" + "User Id=...;Password=...;");

and then after the SQL connection is made and just before I pull data from SQL...

SqlCacheDependency dependency = new SqlCacheDependency(command);

int numberOfMinutes = 3;
DateTime expires = DateTime.Now.AddMinutes(numberOfMinutes);

Current.Response.Cache.SetExpires(expires);
Current.Response.Cache.SetCacheability(HttpCacheability.Public);
Current.Response.Cache.SetValidUntilExpires(true);
Current.Response.AddCacheDependency(dependency);

Previously in the method that this code is in, I accessed SQL and returned a list of objects from SQL. What further steps do I need to do to set up the cache? I'm assuming I have to add the data to the cache somehow and then retrieve it from the cache somehow?

Upvotes: 1

Views: 3561

Answers (1)

D-Shih
D-Shih

Reputation: 46219

You can use the HttpRuntime.Cache cache object

I would write a generic method to GET and SET cache object.

 public T GetOrSetCache<T>
    (string key,T obj, int cacheTime) where T:class,new()
{
    System.Web.Caching.Cache cacheContainer = HttpRuntime.Cache;
    T cacheObj = cacheContainer.Get(key) as T;

    if (cacheObj == null)
    {
        cacheContainer.Insert(key,
            obj,
            null, 
            DateTime.Now.AddMinutes(cacheTime),
            System.Web.Caching.Cache.NoSlidingExpiration);
        cacheObj = obj;
    }

    return cacheObj;
}

When you want to use cache you can do like this on your main code

var data = [read data from data base]
int numberOfMinutes = 3;
data = GetOrSetCache("name1",data,numberOfMinutes );

HttpRuntime.Cache

NOTE

  1. Cache is a key/value` collection

  2. Get instance from cache you need to provide a key.

  3. Set instance into cache you need to provide a key and instance object.

Upvotes: 3

Related Questions