简体   繁体   English

如何在asp.net mvc3中使用缓存?

[英]how use caching in asp.net mvc3?

I have problem with cache in my asp.net mvc3 application. 我的asp.net mvc3应用程序中的缓存存在问题。

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. 因此,在第一次使用时它不起作用,并给我一个错误cache[name]为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; 您绝对不会给cache一个值...并且请注意,如果您希望单独使用常规网络缓存,那不是最好的选择。 perhaps 也许

MemoryCache cache = new MemoryCache(); 

What about using the HttpRuntime.Cache, this example would cache for an hour? 使用HttpRuntime.Cache怎么样,这个示例将缓存一个小时?

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); 学校schoolSettings = CacheProviderFactory.Cache.Get(“ SchoolSettings”)as(School);

Notice that I am using "as" rather than casting the object. 请注意,我使用的是“ as”而不是强制转换对象。 Cast will blow up if the value is null while "as" will just give you a null value which is what you expect. 如果该值为null,则强制转换将失败,而“ as”将仅提供您期望的null值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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