我从最近几个月开始研究C#.net MVC3项目。我没有通过任何教程来了解.net是如何工作的,但我是基于Java和.Net之间的比较而学习的。现在我无法理解一些基本的东西。
这是我的问题我想维护应用程序级缓存(不是会话级别或请求级别),所以我在内存字典对象中创建并想要使用它。不幸的是,即使我在global.asax.cs文件中声明并初始化,缓存对象也会重新初始化每个请求。
这是我的代码请帮帮我。
CachedComponents.cs
==============
public class CachedComponents
{
private static readonly ILog log = LogManager.GetLogger("CachedComponents");
private Dictionary<string, TridionComponent> componentCache = new Dictionary<string, TridionComponent>();
public CachedTridionComponentsRepository()
{
}
public bool IsExistInCache(string uri)
{
return componentCache.ContainsKey(uri);
}
public TridionComponent getCachedItem(string key)
{
if (componentCache.ContainsKey(key))
{
log.Info("[getCachedItem] Cached Item found " + key);
return componentCache[key];
}
else
{
return null;
}
}
public void Add(string key, TridionComponent value)
{
if (componentCache.ContainsKey(key))
{
log.Debug("[Add] Item is already Cached...Cache has been Updated...");
componentCache[key] = value;
}
else
{
log.Debug("[Add] Item has been added to cache");
componentCache.Add(key, value);
}
}
}
Global.asax.cs
=========
protected void Application_Start(object sender, EventArgs e)
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
log4net.Config.XmlConfigurator.Configure();
CachedComponents componentsCache = new CachedComponents();
Application.Add("seeta", "seeta");
Application.Add("componentsCache", componentsCache);
}
MyBusiness.cs
=============
public class MyBusiness
{
private CachedComponets cache = null;
public MyBusiness()
{
if(cache == null)
cache = HttpContext.Cuurent.Application.get("componentsCache");
}
public TridionComponent myBusinessMethod()
{
if (cache.IsExistInCach("uri"))
return cache.getCachedItem("uri");
TridionComponent tc = GetTridionComponent();
cache.Add("uri",tc);
return tc;
}
}
答案 0 :(得分:1)
像对ILog一样设置为static
字典。这应该有效