Seeta Ramayya Vadali
Seeta Ramayya Vadali

Reputation: 465

How to use application specific objects in MVC3?

I have started working on C#.net MVC3 project from last few months. I didn’t go through any tutorial to understand how .net works, but I was learning based on comparison between Java and .Net. Now I couldn’t understand some basic thing.

Here is my question I want to maintain application level cache (not session level or request level), so I created in memory dictionary object and want to play with it. Unfortunately cache objects are reinitializing for every request I guess even though I declared and initialized in global.asax.cs file.

Here is my code please help me.

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;
    }

}

Upvotes: 0

Views: 294

Answers (1)

Iridio
Iridio

Reputation: 9271

Set to static your dictionary as you did with ILog. That should works

Upvotes: 1

Related Questions