views:

599

answers:

1

I am creating a portal where many sites will run of the same MVC application. I have a list of Sites stored in the HttpRuntime.Cache. Is it wrong to access the cache via a static method? Should I instead be passing this on view data?

For example, is this wrong on the view:

<%= SiteHelper.CurrentSite %>

Where the code for SiteHelper is:

public class SiteHelper {
private static object @lock = new object();
private const string siteKey = "FelixSites";

public static Site CurrentSite {
 get {
  var context = HttpContext.Current.Wrap();
  var sites = context.Cache[siteKey] as Site[];
  if (sites == null) {
   lock (@lock) {
    if (sites == null) {
     sites = SiteService.GetSites();
     context.Cache[siteKey] = sites;
    }
   }
  }
  return sites.Single(s => s.Domain == context.Request.UrlReferrer.AbsoluteUri);
 }
}

}

+2  A: 

The only reason it may be bad to use the static property is that breaks the separation of concerns between your view and your model. The model should be the only one concerned with how the data is retrieved - even from objects that are in the same application domain.

While it may seem like overkill to present this data to the view via ViewData it really is the best practice as it preserves the separation of concerns. The more you actively preserve this separation, the better your application will handle refactoring and bug fixes down the road.

Andrew Hare