Roman
Roman

Reputation: 4513

ASP.NET Object Caching in a Class

I'm trying to create a Caching Class to cache some objects from my pages. The purpose is to use the Caching system of the ASP.NET framework but to abstract it to separate class. It seems that the caching doesn't persist.

Any ideas what I'm doing wrong here? Is it possible at all to cache object out side the Page it self?

EDIT: added the code:

Insert to cache

Cache c = new Cache();
c.Insert(userid.ToString(), DateTime.Now.AddSeconds(length), null, DateTime.Now.AddSeconds(length), Cache.NoSlidingExpiration,CacheItemPriority.High,null);

Get from the cache

DateTime expDeath = (DateTime)c.Get(userid.ToString())

I get null on the c.Get, even after I did have the key.

The code is in a different class than the page itself (the page uses it)

Thanks.

Upvotes: 0

Views: 3747

Answers (3)

Matthew Abbott
Matthew Abbott

Reputation: 61617

There are numerous ways you can store objects in ASP.NET

  1. Page-level items -> Properties/Fields on the page which can live for the lifetime of the page lifecycle in the request.
  2. ViewState -> Store items in serialised Base64 format which is persisted through requests using PostBack. Controls (including the page itself - it is a control) can preserve their previous state by loading it from ViewState. This gives the idea of ASP.NET pages as stateful.
  3. HttpContext.Items -> A dictionary of items to store for the lifetime of the request.
  4. Session -> Provides caching over multiple requests through session. The session cache mechanism actually supports multiple different modes.
    • InProc - Items are stored by the current process, which means should the process terminate/recycle, the session data is lost.
    • SqlServer - Items are serialised and stored in a SQL server database. Items must be serialisable.
    • StateServer - Items are serialised and stored in a separate process, the StateServer process. As with SqlServer, items must be serialisable.
  5. Runtime - Items stored in the runtime cache will remain for the lifetime of the current application. Should the applciation get recycled/stop, the items will be lost.

What type of data are you trying to store, and how do you believe it must be persisted?

Right at the beginning of last year I wrote a blog post on a caching framework I had been writing, which allows me to do stuff like:

// Get the user.
public IUser GetUser(string username)
{
  // Check the cache to find the appropriate user, if the user hasn't been loaded
  // then call GetUserInternal to load the user and store in the cache for future requests.
  return Cache<IUser>.Fetch(username, GetUserInternal);
}

// Get the actual implementation of the user.
private IUser GetUserInternal(string username)
{
  return new User(username);
}

That was nearly a year ago, and it has been evolved a bit since then, you can read my blog post about it, let me know if thats of any use.

Upvotes: 7

kerrubin
kerrubin

Reputation: 1616

I have done almost the same things, but with a different code (and it work for me) : (CacheKeys is an enum)

using System;
using System.Configuration;
using System.Web;
using System.IO;
    public static void SetCacheValue<T>(CacheKeys key, T value)
    {
        RemoveCacheItem(key);
        HttpRuntime.Cache.Insert(key.ToString(), value, null,
            DateTime.UtcNow.AddYears(1),
            System.Web.Caching.Cache.NoSlidingExpiration);
    }
    public static void SetCacheValue<T>(CacheKeys key, T value, DateTime expiration)
    {
        HttpRuntime.Cache.Insert(key.ToString(), value, null,
            expiration,
            System.Web.Caching.Cache.NoSlidingExpiration);
    }
    public static void SetCacheValue<T>(CacheKeys key, T value, TimeSpan slidingExpiration)
    {
        HttpRuntime.Cache.Insert(key.ToString(), value, null,
            System.Web.Caching.Cache.NoAbsoluteExpiration,
            slidingExpiration);
    }
    public static T GetCacheValue<T>(CacheKeys key)
    {
        try
        {
            T value = (T)HttpRuntime.Cache.Get(key.ToString());

            if (value == null)
                return default(T);
            else
                return value;
        }
        catch (NullReferenceException)
        {
            return default(T);
        }
    }

Upvotes: 2

Oded
Oded

Reputation: 499402

Your cache reference needs to be accessible to all items in your code - the same reference.

If you are newing up the Cache class every time, you are doing it wrong.

Upvotes: 3

Related Questions