Reputation: 7445
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.
Upvotes: 0
Views: 702
Reputation: 998
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);
}
}
Upvotes: 1
Reputation: 26690
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.
Upvotes: 0
Reputation: 1062780
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();
Upvotes: 2
Reputation: 10416
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);
Upvotes: 1