views:

219

answers:

3

After creating a proof of concept for an ASP.NET MVC site and making sure the appropriate separation of concerns were in place, I noticed that I was making a lot of expensive redundant database calls for information about the current user.

Being historically a desktop and services person, my first thought was to cache the db results in some statics. It didn't take much searching to see that doing this would persist the current user's data across the whole AppDomain for all users.

Next I thought of using HttpContext.Current. However, if you put stuff here when a user is logged out, then when they log in your cached data will be out of date. I could update this every time login/logout occurs but I can't tell if this feels right. In the absence of other ideas, this is where I'm leaning.

What is a lightweight way to accurately cache user details and avoid having to make tons of database calls?

+1  A: 

What you're looking for is System.Web.Caching.Cache

http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx

willbt
To quote MSDN "One instance of this class is created per application domain" which is not what the OP wanted.
AUSteve
I am using HttpContext.Current.Cache to store IPrincipal with FormsAuthentication. Session means another cookie and additional problems.
LukLed
I'm well aware that one instance is created per AppDomain but whats wrong with adding and retrieving from the cache with a unique key for the user. e.g. User-1 where 1 is the Id of the user? It still solves the problem IMO.
willbt
+1  A: 

If the information you want to cache is per-user and only while they are active, then Session is the right place.
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.aspx

AUSteve
Here's another great post working on top of Session: http://stackoverflow.com/questions/343899/
Dinah
A: 

ASP.NET session-state management is good for some situations but when heavy load is put, it tends to create bottlenecks in ASP.NET performance. Read more about it here:

http://msdn.microsoft.com/en-us/magazine/dd942840.aspx

http://esj.com/articles/2009/03/17/optimize-scalability-asp-net.aspx

The solution to avoid bottlenecks is use of distributed caching. There are many free distributed caching solutions in the market like Memcached or NCache Express.

Dont know much about Memcached but i've used NCache Express by Alachisoft, it lets you use ASP.NET caching without requiring any code change.

graham