views:

82

answers:

2

What can I do to avoid the repeated loading of static data every time a page is loaded in ASP.NET MVC2? This is pretty wasteful, and I would like to fix it.

My master page has the typical User Name + Company Name display in the top right corner. But because of the stateless nature of MVC, this data has to be looked up every single time a page is loaded, even though it never changes.

In the old webforms days I would just throw it into Session, but that seems to be discouraged in MVC. Plus the web app runs on a webfarm, so I really do not want to use session.

The web app already has quite a few static data items that get queried on every page load (user currency, user tax rate, etc), so I think a performance gain can be made by loading them only once at login time. I'm just not sure what the correct MVC method is (I am still quite new to MVC).

+3  A: 

I always use the built-in ASP.NET cache for this, set the expiry appropriately and you're good to go.

public void Blah()
{
    var company = HttpRuntime.Cache.Get("Company") as string;
    if (company == null)
    {
        company = FetchCompanyFromDb();
        HttpRuntime.Cache["Company"] = company;
    }

    return this.View(company);
}

Also see this previous question:

http://stackoverflow.com/questions/385986/caching-in-asp-net-mvc

Simon Steele
How well does that work in a web farm scenario? I would guess that Cache is in-memory? So if the user gets pushed from one web box to another, the cache will be gone?
JK
The default cache is in-memory yes. Generally requesting that information once per machine isn't so bad - it's still vastly fewer queries than you had previously. However, let's say that this is hard to calculate information so the request takes a long time. You could then look at Velocity or Memcached which are distributed caches. These can both be used from ASP.NET MVC and would allow you to share the cache, but will be slower to access than the in-memory one.
Simon Steele
A: 

Could you maybe encapsulate your User currency / User name / Tax etc into a user control and then use Output Caching on that?

Jamie
The data also needs to be available in the Controller, so this way probably wont work.
JK