DbContext缓存

DbContext caching

我知道缓存 DbContext 不是个好主意。但我想做得很好。你怎么看这种方式?

public class Context : DbContext
{
    private Context()
    {
    }

    private static WeakReference<Context> _cachedContext;

    public Context Instance
    {
        get
        {
            Context context;
            if (!_cachedContext.TryGetTarget(out context))
            {
                context = new Context();
                _cachedContext.SetTarget(context);
            }
            return context;
        }
    }
}

此代码计划在没有 IDisposable.Dispose 客户端调用的情况下使用。除了单例(反)模式,这会导致什么问题?谢谢

DbContext是缓存。长时间保留它是一个糟糕的主意......它会慢慢消耗你的应用程序的内存,这些内存可能挂在很可能过时的数据上。

它不是为按照您建议的方式使用而设计的。

不要这样

DbContext 是一个临时对象,应该在尽可能小的范围内使用和处理。

 using(var ctx = new MyDbContext())
 {
      //make some changes
      ctx.SaveChanges();
 }

这就是它的设计用途。正确使用它。

This is an XY problem为什么 想要 "cache" DbContext?您认为您将从中获得什么好处?

你永远不应该这样做。 class 不是为了这个。它反而会导致性能问题(取消您认为获得的好处)和附加无效实体后的持续错误 - 您将永远无法再次使用此上下文保存实体,因为更改跟踪器保存实体。

请参阅 Correct usage of EF's DBContext in ASP.NET MVC application with Castle Windsor, Working with DbContext, Managing DbContext the right way with Entity Framework 6: an in-depth guide, Manage the lifetime of dbContext 或在网络上搜索 "entity framework dbcontext lifetime" 时的其他数千个结果中的任何一个。

如果您想缓存数据,则缓存记录本身。现有的解决方案(代码和库)可以帮助您解决这个问题,称为 "second level caching"。不需要自己写。例如参见 [​​=12=].