Linq to SQL DataContext 的多/单实例 [英] Multiple/single instance of Linq to SQL DataContext

查看:21
本文介绍了Linq to SQL DataContext 的多/单实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,其中包含许多不同的类,用于查询和修改一组通用表中的数据.我已经设置了一个 .dbml 文件,它为我们提供了一个 DataContext 类.我的问题是 DataContext 的单个实例是否应该被所有对象使用,或者多个实例是否可以安全使用.我还想知道在单个 DataContext 情况下的线程安全性,以及对其方法的访问是否应该同步.

I have a project with a number of different classes querying and modifying data in a common set of tables. I've set up a .dbml file which provides us with a DataContext class. My question is whether a single instance of the DataContext should be used by all objects, or whether multiple instances are safe to use. I'm also wondering about thread safety in the case of a single DataContext, and whether access to it's methods should be synchronized.

推荐答案

Rick Strahl 有一篇关于您的选择的好文章:http://www.west-wind.com/weblog/posts/246222.aspx.

Rick Strahl has a nice article about your options: http://www.west-wind.com/weblog/posts/246222.aspx.

另见:LINQ to SQL - 你的 DataContext 在哪里?.

对于每种类型的部署,您可能需要略有不同的策略 - Web、桌面、Windows 服务...

You may want a slightly different strategy for each type of deployment - web, desktop, windows service...

总而言之,您的选择是:

Summarized, your options are:

  • 全局数据上下文 - 在多线程环境(包括 Web 应用程序)中很危险.请记住,实例成员不能保证是线程安全的(来自 Bradley Grainger 的 以上答案).
  • 每个线程的DataContext - 复杂.如果您的 DataContext 正在跟踪更改,您必须确保在适当的时间刷新它们.实例化、存储和检索 DataContext 很痛苦.
  • 每个原子操作的数据上下文 - 您无法跟踪更改,因为一个 DataContext 创建一个对象,而另一个更新或删除它.将数据对象附加到新的 DataContext 可能不会像您预期的那样工作.
  • 每个数据对象的 DataContext - 似乎不雅,因为您必须在实例化(创建和附加)和更新/删除(将其从数据对象中拉出并使用它)时对 DataContext 大惊小怪.

我为每个数据对象选择了一个 DataContext.它可能不是最好的解决方案,但它适用于所有部署环境.

I opted for a DataContext per data object. It may not be the fanciest solution but it works in all deployment environments.

这篇关于Linq to SQL DataContext 的多/单实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆