Tip 18 – How to decide on a lifetime for your ObjectContext

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?

时间: 2024-11-04 03:57:42

Tip 18 – How to decide on a lifetime for your ObjectContext的相关文章

MongoDb gridfs-ngnix文件存储方案 - 图片

http://www.cnblogs.com/wintersun/p/4622205.html 在各类系统应用服务端开发中,我们经常会遇到文件存储的问题. 常见的磁盘文件系统,DBMS传统文件流存储.今天我们看一下基于NoSQL数据库MongoDb的存储方案.笔者环境 以CentOS 6.5,MongoDb 2.6.3,  Nginx-1.4.7 为例,您需要了解Linux常用命令. 先来回顾一下MongoDb的内部文件结构 MongoDB在数据存储上按命名空间来划分,一个collection是

论文笔记:目标追踪-CVPR2014-Adaptive Color Attributes for Real-time Visual Tracking

基于自适应颜色属性的目标追踪 Adaptive Color Attributes for Real-Time Visual Tracking 基于自适应颜色属性的实时视觉追踪 3月讲的第一篇论文,个人理解,存在非常多问题,欢迎交流! 这是CVPR2014年的文章. 名字翻译为基于自适应选择颜色属性的实时视觉跟踪.首先理解什么是Adaptive color attributes,文章中colorattributes把颜色分为11类,就是将RGB三种颜色细化为黑.蓝.棕.灰.绿.橙.粉.紫.红.白和

Python全栈开发,Day17 - DOM

本章内容 查找元素 操作 事件 前言 文档对象模型(Document Object Model,DOM)是一种用于HTML和XML文档的编程接口.它给文档提供了一种结构化的表示方法,可以改变文档的内容和呈现方式.我们最为关心的是,DOM把网页和脚本以及其他的编程语言联系了起来.DOM属于浏览器,而不是JavaScript语言规范里的规定的核心内容. 一.查找元素 1.直接查找 document.getElementById    根据ID获取一个标签 document.getElementsBy

iOS开发tips总结

tip 1 :  给UIImage添加毛玻璃效果 func blurImage(value:NSNumber) -> UIImage { let context = CIContext(options:[KCIContextUseSoftwareRenderer:true]) let ciImage = CoreImage.CIImage(image:self) let blurFilter = CIFilter(name:"CIGassianBlur") blurFilter?

VS:101 Visual Studio 2010 Tips

101 Visual Studio 2010 Tips Tip #1        How to not accidentally copy a blank line TO – Text Editor – All Lang – Gen – Apply cut or copy commands to blank lines Tip #2       How to cycle through the Clipboard ring Ctrl+Shift+V (Edit.CycleClipboardRi

blockdev命令

http://www.jb51.net/LINUXjishu/310389.html 这篇文章主要介绍了Linux blockdev命令设置文件预读大小介绍,blockdev 工具允许从命令行调用区块设备控制程序,本文就讲解了它的使用实例,需要的朋友可以参考下 在命令行调用设备的ioctl函数.在Linux系统中,似乎对设备的直接操作只有ioctl函数了.他接受的参数不是太多,而且都是一一对应的. blockdev - 从命令行调用区块设备控制程序 blockdev [options] comm

adaptive color attributes for tracking翻译

本文章是基于目标跟踪的翻译,供大家学习参考! 自适应选择颜色属性的实时视觉跟踪 摘要 视觉跟踪在计算机视觉中是一个很有挑战性的问题,现在最好的(state-of-art) 视觉跟踪器只使用了图片的光照信息或使用简单的颜色表示(RGB 这样的三通道)来表示图片.和视觉跟踪不同的是,在目标识别和检测问题中,结合光照信息和复杂的颜色特征可以提供非常好的表现.由于跟踪问题的复杂性,所需要的颜色特征应该是计算起来比较高效的,并且用有一定的光学不变形,同时具有比较高的判别能力. 这篇文章调查了在tracki

Android学习之高德地图的通用功能开发步骤(二)

周一又来了,我就接着上次的开发步骤(一)来吧,继续把高德地图的相关简单功能分享一下 上次写到了第六步,接着写第七步吧. 第七步:定位 + 地图选点 + 路径规划 + 实时导航 以下是我的这个功能NaviMapActivity的页面布局文件: 1 <?xml version="1.0" encoding="utf-8"?> 2 <RelativeLayout xmlns:android="http://schemas.android.com

iOS开发200个tips总结(一)

tip 1 :  给UIImage添加毛玻璃效果 func blurImage(value:NSNumber) -> UIImage { let context = CIContext(options:[KCIContextUseSoftwareRenderer:true]) let ciImage = CoreImage.CIImage(image:self) let blurFilter = CIFilter(name:"CIGassianBlur") blurFilter?