Search code examples
c#cachinginterface

How can I cache objects and read from memory if it exists instead of database?


I have four classes as following:

public class Section
{
    public int SectionId { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public string MetaTag { get; set; }
    public string MetaDescription { get; set; }
    public string UrlSafe { get; set; }
    public string Header { get; set; }
    public string ImageName { get; set; }
}       

public interface ISectionRepository
{
    List<Section> GetAllSections();
}

public class SectionRepository : ISectionRepository
{
    Context context = new Context();

    public List<Section> GetAllSections()
    {
        return context.Sections.ToList();
    }
}

public class SectionApplication
{
    SectionRepository sectionRepo = new SectionRepository();

    public List<Section> GetAllSections()
    {
        return sectionRepo.GetAllSections();
    }
}

And in my controller, I have

public class SectionController : Controller
{
    SectionApplication sectionApp = new SectionApplication();

    public ActionResult Index()
    {
        return View(sectionApp.GetAllSections());
    }
}

Now, I want to do cache sections on memory for a specific time in order to read sections from cache if it exists, else read it from database.


Solution

  • Simple possible approach, you can use MemoryCache, the code will look like:

    public List<Section> GetAllSections()
    {
        var memoryCache = MemoryCache.Default;
    
        if (!memoryCache.Contains("section"))
        {
            var expiration = DateTimeOffset.UtcNow.AddMinutes(5);
            var sections = context.Sections.ToList();
    
            memoryCache.Add("section", sections, expiration);
        }
    
        return memoryCache.Get("section", null);
    }