Alex D James

7 May 2009 3:44 PM

One of the most common questions we get is how long should an ObjectContext should live. Options often cited include one per:

  • Function
  • Form
  • Thread
  • Application

Plenty of people are asking these types of questions, case in point here is a question on Stackflow. I am sure there are many more buried away on our forums too.

This is a classic it depends type of question.

Lots of factors weigh into the decision including:

  • Disposal:
    Cleanly disposing of the ObjectContext and it’s resources is important. It is also significantly easier if you create a new ObjectContext for each Function, because then you can simply write a using block to ensure resources are disposed appropriately:

using (MyContext ctx = new MyContext())
{
  …
}

  • Cost Of Construction:
    Some people are, quite understandably, concerned about the cost of recreating the ObjectContextagain and again. The reality is this cost is actually pretty low, because mostly it simply involves copying, by reference, metadata from a global cache into the new ObjectContext. Generally I don’t think this cost is worth worrying about, but as always, there will be exceptions to that rule.
  • Memory Usage:
    The more you use an ObjectContext, generally the bigger it gets. This is because it holds a reference to all the Entities it has ever known about, essentially whatever you have queried, added or attached. So you should reconsider sharing the same ObjectContext indefinitely. There are some exceptions to that rule and a workaround, but for the most part these approaches just aren’t recommended.
    • If your ObjectContext only ever does NoTracking queries then it won’t get bigger because the ObjectContext immediately forgets about these entities.
    • You could implement some very explicit tidy-up logic, i.e. implement some sort of Recycle interface, that iterates through the ObjectStateManager detaching entities andAcceptingChanges(..) to discard deleted objects. Note: I’m not recommending this, I’m just saying it should be possible, I have no idea if relative to recreation it will result in any savings. So this might be a good subject for a future blog post.
  • Thread Safety:
    If you are trying to re-use an ObjectContext you should be aware that is not thread safe, i.e. similar to the standard .NET collection classes. If you access it from many threads (e.g. web requests) you will need to insure that you synchronize access manually.
  • Stateless:
    If your services are designed to be stateless, as most web services should be, re-using anObjectContext between requests might not be best because, the leftovers in the ObjectContext from the last call may have subtle effects on your application that you are not expecting.
  • Natural finite lifetimes:
    If you have a natural finite lifetime way of managing an ObjectContext,such as a short lived Form, aUnitOfWork or a Repository, then scoping the ObjectContext accordingly might be the best thing to do.

As you can see there are lots of issues at play.

Most of them tend to point towards a short lived context that isn’t shared.

So that is my recommended rule of thumb.

However as always understanding the reasoning behind a ‘rule of thumb’ will help you know when it is appropriate to go your way.

其他参考

Managing DbContext the right way with Entity Framework 6: an in-depth guide

Why re-initiate the DbContext when using the Entity Framework?

Tip 18 – How to decide on a lifetime for your ObjectContext的更多相关文章

  1. laravel StartSession中间件的实现原理

    1. 打开app\Http\Kernel.php,找到StartSession的位置.这里要说一下,middleware中的中间件是都会被执行的,但执行的顺序我不知道,还需看源码来实现 protect ...

  2. MongoDb gridfs-ngnix文件存储方案

          在各类系统应用服务端开发中,我们经常会遇到文件存储的问题. 常见的磁盘文件系统,DBMS传统文件流存储.今天我们看一下基于NoSQL数据库MongoDb的存储方案.笔者环境 以CentOS ...

  3. VS:101 Visual Studio 2010 Tips

    101 Visual Studio 2010 Tips Tip #1        How to not accidentally copy a blank line TO – Text Editor ...

  4. iOS开发200个tips总结(一)

    tip 1 :  给UIImage添加毛玻璃效果 func blurImage(value:NSNumber) -> UIImage { let context = CIContext(opti ...

  5. blockdev命令和blkid命令

    blockdev命令和blkid命令 http://www.jb51.net/LINUXjishu/310389.html block相关的命令 这篇文章主要介绍了Linux blockdev命令设置 ...

  6. MongoDb gridfs-ngnix文件存储方案 - 图片

    http://www.cnblogs.com/wintersun/p/4622205.html 在各类系统应用服务端开发中,我们经常会遇到文件存储的问题. 常见的磁盘文件系统,DBMS传统文件流存储. ...

  7. iOS开发tips总结

    tip 1 :  给UIImage添加毛玻璃效果 func blurImage(value:NSNumber) -> UIImage { let context = CIContext(opti ...

  8. [No0000135]程序员修炼之道 Tips

    这一篇文章其实就是记录程序员修炼之道中的所有 Tips, 我讲会在之后的每周实践两个 Tip, 并对这两个 Tips 进行补充和说明自己的体会, 最终成为书中所说的卓有成效的程序员. Tip 1: C ...

  9. blockdev命令 blkid命令 lsblk命令

    blockdev命令  blkid命令  lsblk命令 http://www.jb51.net/LINUXjishu/310389.html block相关的命令 这篇文章主要介绍了Linux bl ...

随机推荐

  1. Leetcode分类总结(Greedy)

    贪心类题目目前除了正则匹配(Wildcard Matching)(据说其实是DP)那道还没做其他的免费题目都做了,简单做个总结. 贪心的奥义就是每一步都选择当前回合”可见范围“(即可得知的信息)内的最 ...

  2. 2331: [SCOI2011]地板 插头DP

    国际惯例的题面:十分显然的插头DP.由于R*C<=100,所以min(R,C)<=10,然后就可以愉悦地状压啦.我们用三进制状压,0表示没有插头,1表示有一个必须延伸至少一格且拐弯的插头, ...

  3. 4712: 洪水 基于链分治的动态DP

    国际惯例的题面:看起来很神的样子......如果我说这是动态DP的板子题你敢信?基于链分治的动态DP?说人话,就是树链剖分线段树维护DP.既然是DP,那就先得有转移方程.我们令f[i]表示让i子树中的 ...

  4. CF1106F Lunar New Year and a Recursive Sequence 线性递推 + k次剩余

    已知\(f_i = \prod \limits_{j = 1}^k f_{i - j}^{b_j}\;mod\;998244353\),并且\(f_1, f_2, ..., f_{k - 1} = 1 ...

  5. php urlencode函数 (中文字符转换为十六进制)

    urlencode()函数原理就是首先把中文字符转换为十六进制,然后在每个字符前面加一个标识符%. urldecode()函数与urlencode()函数原理相反,用于解码已编码的 URL 字符串,其 ...

  6. C++ 函数模板基础知识

    为什么要引入模板:为了避免代码重复,程序员可以编写脱离数据类型通用模板. 模板的分类:函数模板 + 类模板 注意:模板的声明或定义只能在全局,命名空间或类范围内进行.不能在函数内进行,比如不能在mai ...

  7. 在Windows系统配置Jekyll

    Jekyll 是一个简单的网站静态页面生成工具.由于是用Ruby语音编写的,所以在Windows系统上配置起来还是稍微有点繁琐的.具体过程如下: 安装Ruby:在Windows系统上当然使用rubyi ...

  8. java定义一个二维数组

    https://zhidao.baidu.com/question/2052557356110840027.html https://blog.csdn.net/houpengfei111/artic ...

  9. .net framework 4.6 asp.net mvc 使用NLog

    NUGET添加NLog和NLog.Config的引用 配置NLog.config <?xml version="1.0" encoding="utf-8" ...

  10. 关于ADO.Net SqlConnection的性能优化

    Connections Database connections are an expensive and limited resource. Your approach to connection ...