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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With