views:

84

answers:

2

In asp.net the major data stores are application, session and we also have the object cache. I have used common sense hints/tips (e.g. never put users specific data in application, never put unmanaged resources in session etc. etc.) but to be honest I have never come across any recommendations and examples for when to use what in MSDN or from prominent figures like Haack and the Gu that cover all three together (e.g. Google's first hit to MSDN talks about using application as a global cache, if that's the case, what's the object cache for ?

Also something that I find seldom discussed is comparison in scenario, for example I know its easy to unnecessary load up memory usage with over use of session, but what happens if you used the object cache as an alternative to store the same data ?

Edit: This is the best information I have found so far: http://msdn.microsoft.com/en-us/library/ff647787.aspx

A: 

Use Session to store user-specific information, since the framework automatically associates each session store with a specific user.

Use the Object Cache for information that can be cached once and reused across the entire application or across a set of users. If you store user-specific data in the Object Cache then you'll have to invent some mechanism to associate cache entries. Not only would this require extra work on your behalf, but you might do it in such a way that increases the likelihood of a nefarious user somehow doing something akin to session spoofing.

I don't know when you'd ever need to use the Application object. If I'm not mistaken, the Application object is more of a relic from classic ASP than anything else.

Another form of caching that can be just as important is per-request caching via the HttpContext.Items collection. This allows you to cache data for the lifetime of a request and is useful if you keep requesting the same data during a single request (such as from different User Controls on the page). For more information on this approach, see HttpContext.Items - a Per-Request Cache Store.

Scott Mitchell
A: 

I'd suggest creating a wrapper class, at least for the session, if those get used throughout your code. That way, you can inject an instance of the class to do the real work, and use a mocked version for unit tests. I did this for a large project where the session was widely used, and it worked out rather well.

You can combine this with the facade pattern - the wrapper will provide specific methods that you needs, instead of exposing the general interface. As an example, the session takes objects and returns objects, it is not strongly typed. The wrapper can have strongly typed add and get methods.

Grant Palin