c# - 如果它存在而不是数据库,我如何缓存对象并从内存中读取?

标签 c# caching interface

我有以下四个类:

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

在我的 Controller 中,我有

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

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

现在,我想在特定时间内在内存上缓存部分,以便从缓存中读取部分(如果存在),否则从数据库中读取。

最佳答案

简单可行的方法,您可以使用MemoryCache ,代码将如下所示:

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", section, expiration);
        }

        return memoryCache.Get("section", null);

    }

关于c# - 如果它存在而不是数据库,我如何缓存对象并从内存中读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14999599/

相关文章:

c# - 尝试编写鼠标单击代码时 PInvoke 签名出错

c# - 从 Master 更新内容页面

c++ - 线程本地内存,使用 std::string 的内部缓冲区作为 c 风格的临时内存

ruby-on-rails - Redis 中缓存的最佳 expire_in 值

Azure Redis 缓存突然空了?

c# Interface 命名空间前缀

java - 使用接口(interface)在2个java类之间进行通信

c# - Parse 诉 TryParse

c# - 如何使用 EF6 Code First 将外键属性公开给具有导航属性的现有实体

c# - List<Interface> 的 object[] 返回 null