Ham*_*eza 10 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();
}
}
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,我有
public class SectionController : Controller
{
SectionApplication sectionApp = new SectionApplication();
public ActionResult Index()
{
return View(sectionApp.GetAllSections());
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我想在内存上缓存部分一段特定的时间,以便从缓存中读取部分(如果存在),否则从数据库中读取它.
cuo*_*gle 20
简单可行的方法,你可以使用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);
}
Run Code Online (Sandbox Code Playgroud)