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 ...
随机推荐
- 探秘Tomcat(一)
前言:有的时候自己不知道自己是井底之蛙,这并没有什么可怕的,因为你只要蜷缩在方寸之间的井里,无数次的生活轨迹无非最终归结还是一个圆形:但是可怕的是有一天你不得不从井里跳出来生活,需要重新审视井以外的生 ...
- .Net机试题——编写一个BS架构的多层表结构的信息管理模块
要求: 编写一个BS架构的多层表结构的信息管理模块,用户体验需要注意.包含错误处理,需要最终能完整的跑起来.页面可以不美化,但是整洁还是必须的.在不能完成详细功能需求的情况下优先保证基本功能. 1 ...
- CentOS下bond网卡聚合与网桥结合
需求:服务器配置bond多网卡聚合,然后KVM需要使用到网桥,那么需要做到网桥绑定到bond网卡上. 实现核心: 1.bond配置参考:https://www.cnblogs.com/EasonJim ...
- Mac 安装配置nexus2.6 搭建Maven的中央仓库
今天配置java 环境,安装nexus 百度了好久才安装好,所以特别写下来 分享给同样遇到问题的你.废话不多说,直接上步骤 前置条件 :已经安装了JDK 下载nexus(http://www.sona ...
- SVN clean失败解决方法【转】
原文地址:http://blog.csdn.net/victory08/article/details/42100325/ svn执行clean up后出现提示:svn cleanup failed– ...
- 使用promise 和 generator来管理工作流
根据p219的代码改编 示例代码如下 function oneStep(value){ return new Promise(function(resolve, reject){ resolve('o ...
- AndroidStudio下加入百度地图的使用 (三)——API基本方法及常量属性
上一章中我们已经完成定位功能,这一章向大家介绍一下常用的方法及常量属性的意思. (1) 手势方法 缩放: setZoomGesturesEnabled() 俯视: setOverlookingGest ...
- 职场之KPI
当一个公司开始执行KPI考核的时候,任何人的工作性质就发生了变化,而处于底层的员工就惨了,因为一个公司的资源是有限的,一个人的精力也是有限的,当你和你上司负责不同的项目时,而当你的所谓产品经理负责两个 ...
- Android Studio 3.1 正式版
欢迎大家推荐自己在Android开发过程中用的好用的工具.学习开发教程.用到设计素材.如果你觉得本站对你有用,你可以点击底部的分享按钮,把本站分享到社交网络让你的小伙伴和更多的人知道. 或者可以考虑捐 ...
- Java 对字符串数据进行MD5/SHA1哈希散列运算
Java对字符串数据进行MD5/SHA1哈希散列运算 [java] view plain copy package cn.aibo.test; import java.security.Message ...