Abe Miessler
Abe Miessler

Reputation: 85126

Am I using cache correctly?

I have an application where every single page uses a set of data that is stored in the database. To avoid making a call to the database every time I need the data, I decided to put it in HttpRuntime.Cache. I am making the call to the DB and caching the data in the constructor for my Controller.cs file, which is the only place this data is used.

The above method works, but I'm wondering if this is the correct place/way to load my cache?

Also, the data is the same for every user and will change maybe a few times a year.

Upvotes: 1

Views: 101

Answers (1)

Hadi Eskandari
Hadi Eskandari

Reputation: 26444

Caching the data, and consuming the cached data are two different concerns. Supposing you have this interface to fetch the data:

public interface IDataRepository 
{
    List<Data> GetData();
}

you can have two implementations, one fetching the data from the database, another just acting as a proxy and caching the data, if necessary:

public class DataRepository : IDataRepository
{
    public virtual List<Data> GetData()
    {
        //Hit the database and get the data
    }
}

public class CachedDataRepository : DataRepository, IDataRepository
{
    public override List<Data> GetData()
    {
        if(!IsCachedAlready())
        {
            var data = base.GetData();
            AddToCache(data);
        }

        return DataFromCache();
    }
}

You can now use the same interface and not worry if the data that you're use in the controller is cached or not.

Upvotes: 2

Related Questions