使用存储库模式进行实体框架缓存

Joe*_*Joe 6 .net caching frameworks entity

如果我想在使用存储库模式和实体框架时实现缓存,我不能只在Entity Framework之外做一些简单的逻辑来处理缓存吗?

例如

if(Cache[ProductsKey] != null)
{
    return ConvertToProducts(Cache[ProductsKey]);
}
else
{
    var products = repository.Products;
    Cache[ProductsKey] =  products;
    return products;
}
Run Code Online (Sandbox Code Playgroud)

似乎很多人都过于复杂了.或者这样做会以某种方式限制?

Afs*_* Gh 4

我更喜欢我的存储库是干净的。如果需要的话,我更喜欢在我的服务层中实现缓存

所以我100%同意你的样本。您的存储库返回产品(通过运行查询),您可以将其缓存或不缓存在其他层中。

PS:我假设您在需要时启动对象上下文(会话开始)并在会话结束时处置它。