22

I am working on mvc4 web application. I want to cache some database queries results and views on server side. I used-

HttpRuntime.Cache.Insert()

but it caches the data on client side. Please help.

0

1 Answer 1

42

I'm using MemoryCache to store query results, and it's working fine so far.
Here are a few links that I've used to implement it.
- Using MemoryCache in .NET 4.0 (codeproject)
- Using MemoryCache in .NET 4.0 (blog entry)

As I read them now, I find them not that clear, so maybe there is a better link that I've lost somewhere.
Here is a sample of my code which I hope is clear enough so that you see how it works

public static class AgencyCacheManager
{
    private static MemoryCache _cache = MemoryCache.Default;

    public static List<RefAgency> ListAgency
    {
        get
        {
            if (!_cache.Contains("ListAgency"))
                RefreshListAgency();
            return _cache.Get("ListAgency") as List<Agency>;
        }
    }

    public static void RefreshListAgency()
    {
        var listAgency = GetAllComplete();

        CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
        cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddDays(1);

        _cache.Add("ListAgency", listAgency, cacheItemPolicy);
    }
}

And to retrieve the list from cache

public Agency FindBy(string agencyId)
{
    return AgencyCacheManager.ListAgency.SingleOrDefault(x => x.AgencyPartnerCode == agencyId);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.