[英]In ASP.Net MVC, is using static methods to look up cached objects on views bad practice?
I am creating a portal where many sites will run of the same MVC application. 我正在创建一个门户网站,其中许多网站将运行相同的MVC应用程序。 I have a list of Sites stored in the HttpRuntime.Cache.
我有一个存储在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: 例如,视图上的这个错误:
Where the code for SiteHelper is: SiteHelper的代码是:
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);
}
}
} }
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. 虽然通过
ViewData
将这些数据呈现给视图似乎有点过分,但它确实是最佳实践,因为它保留了关注点的分离。 The more you actively preserve this separation, the better your application will handle refactoring and bug fixes down the road. 您越积极地保留这种分离,您的应用程序将越好地处理重构和错误修复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.