Как использовать специфичные для приложения объекты в MVC3? - PullRequest
0 голосов
/ 07 марта 2012

Я начал работать над проектом 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;
    }

}

1 Ответ

1 голос
/ 07 марта 2012

Установите static ваш словарь, как вы делали с ILog.Это должно работать

...