的DbContext缓存 [英] DbContext caching

查看:499
本文介绍了的DbContext缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道的DbContext的缓存是不是好主意。但我想这样做的罚款。你怎么看待这样

I know the caching of DbContext is not good idea. But I would like to do it fine. What do you think about this way?

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在客户端呼叫使用。有什么问题这可能会导致除单(反)模式?谢谢你。

This code is planned to be used without IDisposable.Dispose calling in the client-side. What problems this can cause except singleton (anti)pattern? Thanks.

推荐答案

的DbContext 是一个缓存。保持它搁置了很长一段时间是一个可怕的想法...慢慢会消耗你的应用程序的内存挂到的数据可能是过时的。

The DbContext is a cache. Keeping hold of it for a long time is a terrible idea... it will slowly consume your application's memory hanging on to data that may well be stale.

它不被设计在你提出的方式被使用。

It was not designed to be used in the way you propose.

不要这么做。

Don't do it.

A 的DbContext 是应该使用,并在最小的范围内尽可能处置临时对象。

A DbContext is a transient object that should be used and disposed of in the smallest scope possible.

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



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

That's how it was designed to be used. Use it properly.

这篇关于的DbContext缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆