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. 论文--Topic-Sensitive PageRank

    背景 原有的PageRank方法:通过web上链接结构信息得到页面之间相对的重要性,和特定的查询内容无关 论文涉及到的其他算法 HITS Hilltop,处理常见的流行查询 popular query ...

  2. SQLserver 字符串转换日期,日期转换成为字符串

    sqlserver 日期与字符串之间的转换   该文章摘自:http://www.cnblogs.com/windphoenix/archive/2013/04/26/3044784.html 字符转 ...

  3. Educational Codeforces Round 47 (Div 2) (A~G)

    目录 Codeforces 1009 A.Game Shopping B.Minimum Ternary String C.Annoying Present D.Relatively Prime Gr ...

  4. BZOJ.3638.CF172 k-Maximum Subsequence Sum(模拟费用流 线段树)

    题目链接 各种zz错误..简直了 /* 19604kb 36292ms 题意:选$k$段不相交的区间,使其权值和最大. 朴素线段树:线段树上每个点维护O(k)个信息,区间合并时O(k^2),总O(mk ...

  5. php curl请求https 返回无结果|false|errno:35

    1 SSL: certificate subject name 'WMSvc-GWAMSERVER02' does not match target host name 把curl_setopt($c ...

  6. unity3d 射线的原理,基础用法

    射线:射线是3D世界中一个点向一个方向发射的一条无终点的线,在发射轨迹中与其他物体发生碰撞时,它将停止发射 . Ray射线类和RaycastHit射线投射信息类是射线中常用的两个工具类. 用途:射线多 ...

  7. 大数据实践:ODI 和 Twitter (二)

    大数据实践:ODI和Twitter(二) 在前面的文章中,我们已经使用flume将数据从twitter抓取到Hive中,现在我们来看看ODI(Oracle Data Integrator)如何在HIV ...

  8. 大文件拆分方案的java实践(附源码)

    引子 大文件拆分问题涉及到io处理.并发编程.生产者/消费者模式的理解,是一个很好的综合应用场景,为此,花点时间做一些实践,对相关的知识做一次梳理和集成,总结一些共性的处理方案和思路,以供后续工作中借 ...

  9. Java 多线程(七) 线程间的通信——wait及notify方法

    线程间的相互作用 线程间的相互作用:线程之间需要一些协调通信,来共同完成一件任务. Object类中相关的方法有两个notify方法和三个wait方法: http://docs.oracle.com/ ...

  10. Android典型界面设计(7) ——DrawerLayout+Fragement+ViewPager+PagerTabStrip实现双导航

    一.问题描述 在Android典型界面设计(3)的我们实现了双导航效果,即外层底部导航和内部区域的头部导航,如网易新闻等很多应用采用了这种导航,但Google提供DrawerLayout可实现抽屉式导 ...