Using the ASP.NET Cache outside of ASP.NET
Travis was talking about using the ASP.NET Cache object/subsystem outside of ASP.NET. I found it a little creepy as I've had all sorts of trouble trying to to Mock testing with ASP.NET outside of IIS and ended up using Cassini back in the day.
He convinced me though, check out the sample code on his site. I also started a conversation on a list server and here's what came of that:
Yes, it's fairly common (and easy) to do. You just have to include a reference to the System.Web assembly in non-web applications; which may have led to your "creep out" – for what it’s worth it used to do the same to me :)
FWIW, I believe (from memory) the recommended way you grab a reference outside of a web application is:
using System.Web;
using System.Web.Caching;
…
Cache cache = HttpRuntime.Cache;
<snip>...the Cache is just too important of a feature to only belong to ASP.NET.
Scott Stanfield said:
The biggest problem you'll run into using the cache outside of a web app is simply the namespace: System.Web. People freak out in code reviews. We got a lot of trash talk from the J2EE world on PetShop because of this.
Chris Kinsman said he seemed to remember some trouble with the Cache not sticking around in memory when used outside of ASP.NET, but that hasn't been substantiated. I'm going to dig more.
Adding System.Web to your non-web project is a good way to get folks to panic. Another is adding a reference to Microsoft.VisualBasic in a C# application. Both are reasonable and darned useful things to do, though.
About Scott
Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.
About Newsletter
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag2/html/caching1.asp
{
private CacheProvider(){};
public static Instance
{
get
{
return (HttpContext.Current == null) ? HttpRuntime.Cache : HttpContext.Current.Cache;
}
}
}
or the 2.0 version
return (HttpContext.Current ?? HttpRutime.Cache);
Honestly, just a simple static object that supports sliding expirations? Seems that that SQL Server 2005 folks would have been clamoring to get SQL Server Cache invalidation working for winforms/WPF applications too.
So always use HttpRuntime.Cache istead of HttpContext.Current.Cache ;) thanks
karl
The problem with this one, as I recall, is mostly in setup.
It'd be nice to see BuildProviders pulled out, as well.
Re Cache vs EntLib: Cache has one singular advantage -- it's already there. As much as I pimped EntLib a year ago, it's a download-modify-and-compile project. With all do respect to the hard work that went into it: if I wanted that, I could use Java. I prefer my batteries included.
Comments are closed.
I've never used the VisualBasic namespace, what's in there that's useful? Removal of short-circuiting? :P