Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Has something changed in caching data in ASP.NET-MVC3?

I need an application level cache in my MVC3 project.

I want to use something like this in a controller:

using System.Web.Caching;    

protected IMyStuff GetStuff(string stuffkey)
{
    var ret = Cache[stuffkey];
    if (ret == null)
    {
        ret = LoadStuffFromDB(stuffkey);
        Cache[stuffkey] = ret;
    }
    return (IMyStuff)ret;
}

This fails because Cache["foo"] don't compile as "System.Web.Caching.Cache is a 'type' but used like a 'variable'".

I see that Cache is a class, but there are quite a few examples on the net when it is used like Session["asdf"] in the controller like it is a property.

What am I doing wrong?

like image 544
vinczemarton Avatar asked Dec 22 '22 12:12

vinczemarton


1 Answers

There is a property named Session in controller but there is no property named Cache. You should use HttpRuntime.Cache static property in order to get Cache object. For example:

using System.Web.Caching;    

protected IMyStuff GetStuff(string stuffkey)
{
    var ret = HttpRuntime.Cache[stuffkey];
    if (ret == null)
    {
        ret = LoadStuffFromDB(stuffkey);
        HttpRuntime.Cache[stuffkey] = ret;
    }
    return (IMyStuff)ret;
}
like image 100
Egor4eg Avatar answered Jan 18 '23 00:01

Egor4eg