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 ...
随机推荐
- BZOJ.2287.[POJ Challenge]消失之物(退背包)
BZOJ 洛谷 退背包.和原DP的递推一样,再减去一次递推就行了. f[i][j] = f[i-1][j-w[i]] + f[i-1][j] f[i-1][j] = f[i][j] - f[i-1][ ...
- 潭州课堂25班:Ph201805201 爬虫基础 第四课 Requests (课堂笔记)
优雅到骨子里的Requests 1528811134432 简介 上一篇文章介绍了Python的网络请求库urllib和urllib3的使用方法,那么,作为同样是网络请求库的Request ...
- [洛谷3375]【模板】KMP字符串匹配
思路: KMP模板. #include<cstdio> #include<cstring> ],s2[]; int main() { scanf("%s%s" ...
- 20172302 《Java软件结构与数据结构》第一周学习总结
2018下半年学习总结博客总目录:第一周 教材学习内容总结 第一章 概述 1.软件质量 软件工程(Software Engineering)是一门关于高质量软件开发的技术和理论的学科. 软件质量从以下 ...
- MAC自动脚本
链接: crontab 详细用法 定时任务 Linux crontab命令 定时任务 用法详解以及no crontab for root解决办法
- mongodb通过profile来监控数据
mongodb可以通过profile来监控数据,进行优化.查看当前是否开启profile功能用命令db.getProfilingLevel() 返回level等级,值为0|1|2,分别代表意思:0代表 ...
- 《西部世界》S2E9:蝶化庄周,浮生若梦
原以为第九集能解开本季大半的疑惑,结果还是被骗了……看来<西部世界>铁了心要把主要秘密都放在大结局里揭晓,大家就再等一周吧. 尽管如此,本集还是说清了不少谜团:比如威廉和格蕾丝的真实身份, ...
- Gson 与 fastJson 在使用上的差异(fastJson的优点)
一.android 常用的json解析方式 Android 开发上常用的json解析方式有:Gson, fastJson,jackson. 因为jackjson jar包会比较大点(700+k),Gs ...
- 理解TCP之Keepalive
理解HTTP之keep-alive 在前面一篇文章中讲了TCP的keepalive,这篇文章再讲讲HTTP层面keep-alive.两种keepalive在拼写上面就是不一样的,只是发音一样,于是乎大 ...
- oracle获取今年在内的前几年、后几年
前几年 select to_char(sysdate, 'yyyy') - level + 1 years from dual connect by level <= num num:即想获取几 ...