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 ...
随机推荐
- Luogu2586 [ZJOI2008]杀蚂蚁 ---- 模拟
Luogu2586 [ZJOI2008]杀蚂蚁 题意 还是一道大模拟 https://www.luogu.org/problemnew/show/P2586 大概就是炮塔大蚂蚁的故事 下载这个游戏ht ...
- android studio的汉化 教程 及解析
android studio的汉化 教程 及解析 作者:韩梦飞沙 Author:han_meng_fei_sha 邮箱:313134555@qq.com E-mail: 313134555 @qq.c ...
- 潭州课堂25班:Ph201805201 WEB 之 页面编写 第四课 登录注册 (课堂笔记)
index.html 首页 <!DOCTYPE html> <html lang="en"> <head> <meta charset=& ...
- [POI2011]Inspekcja
[POI2011]Inspekcja 题目大意: 给你一棵\(n(n\le10^6)\)个点的树,\(s\)为起点.每次选择一个点作为目标点\(t_i\),沿最短路走到\(t_i\)再走回\(s\)( ...
- js中for in,of区别
let x; let a = ['a','b','c'] let b = {name:'LIUNAN',age:19} for(x of a){ document.write(x) } for(x i ...
- java计算某个坐标是否在范围内
java电子围栏 圆.矩形.多边形算法 http://blog.csdn.net/deepak192/article/details/79402694/ java-经纬度有关的计算(半径内的经纬度范围 ...
- unity8个入门代码
01,基本碰撞检测代码 function OnCollisionEnter(theCollision:Collision){ if(theCollision.gameObject.name==&quo ...
- iOS CrashLog Analysis
链接: iOS友盟崩溃日志定位代码 [友盟统计报表解读]之错误分析iOS版 DYSMTool Download Address 利用友盟和dsym分析发布app用户错误 iOS -- 友盟工具进行Cr ...
- Git:本地建服务器及入门使用方法
1. 安装与配置Git服务器 sudo apt-get install git 1.1 注册一个git账号, 用于运行和维护git sudo adduser git 1.2 创建证书登录: 收集所有需 ...
- Launch 启动全屏 隐藏上方状态栏
1:statusBar字体为白色 在plist里面设置View controller-based status bar appearance 为 NO:设置statusBarStyle 为 UISta ...