简体   繁体   中英

how use caching in asp.net mvc3?

I have problem with cache in my asp.net mvc3 application.

My code

using System.Web.Caching;
...
class RegularCacheProvider : ICacheProvider
{
    Cache cache ;

    public object Get(string name)
    {
        return cache[name];
    }

    public void Set(string name, object value)
    {
        cache.Insert(name, value);
    }

    public void Unset(string name)
    {
        cache.Remove(name);
    }
}

And I use singleton for give value for it :

School schoolSettings = (School)CacheProviderFactory.Cache.Get("SchoolSettings");
            if (schoolSettings == null)
            {
                CacheProviderFactory.Cache.Set("SchoolSettings", someObject);
            }

So in first use it does not work and give me an error cache[name] is null.

What I'm doing wrong?

Any help would be appreciated.

At no point have you given cache a value... and note that the regular web cache probably isn't your best bet if you want it separate; perhaps

MemoryCache cache = new MemoryCache(); 

What about using the HttpRuntime.Cache, this example would cache for an hour?

HttpRuntime.Cache.Add("SchoolSettings", someObject, null, DateTime.Now.AddHours(1),
                       System.Web.Caching.Cache.NoSlidingExpiration,
                       System.Web.Caching.CacheItemPriority.Normal, null);

Try the following code. it works fine for my project

 using System.Runtime.Caching;

    public class RegularCacheProvider : ICacheProvider
        {
            private ObjectCache Cache { get { return MemoryCache.Default; } }

            object ICacheProvider.Get(string key)
            {
                return Cache[key];
            }

            void ICacheProvider.Set(string key, object data, int cacheTime = 30)
            {
                var policy = new CacheItemPolicy {AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime)};
                Cache.Add(new CacheItem(key, data), policy);
            }

            void ICacheProvider.Unset(string key)
            {
                Cache.Remove(key);
            }
        }

Change the code where you check for the value as follow:

School schoolSettings = CacheProviderFactory.Cache.Get("SchoolSettings") as (School);

Notice that I am using "as" rather than casting the object. Cast will blow up if the value is null while "as" will just give you a null value which is what you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM