Tip 18 – How to decide on a lifetime for your ObjectContext
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的更多相关文章
- laravel StartSession中间件的实现原理
1. 打开app\Http\Kernel.php,找到StartSession的位置.这里要说一下,middleware中的中间件是都会被执行的,但执行的顺序我不知道,还需看源码来实现 protect ...
- MongoDb gridfs-ngnix文件存储方案
在各类系统应用服务端开发中,我们经常会遇到文件存储的问题. 常见的磁盘文件系统,DBMS传统文件流存储.今天我们看一下基于NoSQL数据库MongoDb的存储方案.笔者环境 以CentOS ...
- VS:101 Visual Studio 2010 Tips
101 Visual Studio 2010 Tips Tip #1 How to not accidentally copy a blank line TO – Text Editor ...
- iOS开发200个tips总结(一)
tip 1 : 给UIImage添加毛玻璃效果 func blurImage(value:NSNumber) -> UIImage { let context = CIContext(opti ...
- blockdev命令和blkid命令
blockdev命令和blkid命令 http://www.jb51.net/LINUXjishu/310389.html block相关的命令 这篇文章主要介绍了Linux blockdev命令设置 ...
- MongoDb gridfs-ngnix文件存储方案 - 图片
http://www.cnblogs.com/wintersun/p/4622205.html 在各类系统应用服务端开发中,我们经常会遇到文件存储的问题. 常见的磁盘文件系统,DBMS传统文件流存储. ...
- iOS开发tips总结
tip 1 : 给UIImage添加毛玻璃效果 func blurImage(value:NSNumber) -> UIImage { let context = CIContext(opti ...
- [No0000135]程序员修炼之道 Tips
这一篇文章其实就是记录程序员修炼之道中的所有 Tips, 我讲会在之后的每周实践两个 Tip, 并对这两个 Tips 进行补充和说明自己的体会, 最终成为书中所说的卓有成效的程序员. Tip 1: C ...
- blockdev命令 blkid命令 lsblk命令
blockdev命令 blkid命令 lsblk命令 http://www.jb51.net/LINUXjishu/310389.html block相关的命令 这篇文章主要介绍了Linux bl ...
随机推荐
- c#textBox控件限制只允许输入数字及小数点
在textboxd的事件中的 KeyPress 事件,这样双击进入代码:输入以下代码 即可 //判断按键是不是要输入的类型. || () && ( && () e.Ha ...
- java的关键字与保留字
1,Java 关键字列表 (依字母排序 共50组): abstract, assert, boolean, break, byte, case, catch, char, class, const(保 ...
- SpringBoot在自定义类中调用service层等Spring其他层
解决方案: 1.上代码 @Component public class ServerHandler extends IoHandlerAdapter { @Autowired protected He ...
- WinPython
WinPython http://winpython.github.io/
- 用ndk-stack分析应用native程序异常crash掉
adb logcat | "/home/hxl/bin/android-ndk-r10d/ndk-stack" -sym "/home/hxl/plu/BadGame/p ...
- jquery预加载的几种方式
实际编写前端页面时,有时候希望一打开某个页面就加载一些方法.下面是4种预加载方法. ①页面加载完之前执行,与嵌入的js加载方式一样(写jquery插件的时候使用) (function ($) { al ...
- 一篇文章让你学透Linux系统中的more命令
Linux 下有很多实用工具可以让你在终端界面查看文本文件.其中一个就是 more. more 跟我之前另一篇文章里写到的工具 —— less 很相似.它们之间的主要不同点在于 more 只允许你向前 ...
- 微软BI 之SSIS 系列 - 使用 Multicast Task 将数据同时写入多个目标表,以及写入Audit 与增量处理信息
开篇介绍 在 SSIS Data Flow 中有一个 Multicast 组件,它的作用和 Merge, Merge Join 或者 Union All 等合并数据流组件对比起来作用正好相反.非常直观 ...
- 微软BI 之SSIS 系列 - 导出数据到 Excel 2013 的实现
开篇介绍 碰到有几个朋友问到这个问题,比较共性,就特意写了这篇小文章说明一下如何实现在 SSIS 中导出数据到 Office Excel 2013 中.通常情况下 2013 以前的版本大多没有问题,但 ...
- 《Unix&Linux大学教程》学习笔记5 :正则表达式
1:Unix下正则表达式规则