MSDN Blogs > Data Access blog > A ConnectionScope class. [Alazel Acheson]
A ConnectionScope class. [Alazel Acheson]
Rate This
MSDNArchive
14 Feb 2006 12:48 PM
Comments20
I’ve heard a few comments from people who would like an easier way to manage connection lifetime & use across multiple methods. Most often, the problem is due to using a TransactionScope at an higher level, but opening and closing connections inside the methods – generally resulting in a distributed transaction unless you manually move a single connection around. For example:
void OuterMethod() { using (TransactionScope tx = new TransactionScope(TransactionScopeOption.RequiresNew, opts)) { InnerMethod("select * from testtable"); InnerMethod("update testtable set col1 = N'new value'"); tx.Complete(); } }
To avoid the distributed transaction, you would need to create the connection in the OuterMethod and pass it in as a parameter (somewhat tedious) or assign it to a member variable (somewhat risky, as you are then probably maintaining a reference to the connection beyond it’s intended lifetime).
I've implemented a simple scope class for db connections that can simplify the process (see the attached file). Feel free to use this class directly or modify it as needed.
To use it, simply create a new DbConnectionScope in the OuterMethod and follow one of the two patterns for getting your connection to the inner scope:
Create, open and place your connection into the scope prior to use with AddConnection (generally the OuterMethod), assigning it a key for identification. In the InnerMethod, pull it out using GetConnection and assign it to your command before executing.
Use GetOpenConnection() in the InnerMethod and the scope will construct & open your connection as needed, using the connection string as the key.
The example, re-written using the second pattern, looks like this:
void OuterMethod() {
using (TransactionScope tx = new TransactionScope(TransactionScopeOption.RequiresNew, opts)) {
using (DbConnectionScope db = new DbConnectionScope()) {
InnerMethod("select * from testtable");
InnerMethod("update testtable set col1 = N'new value'");
This class is only something you’d want to use only if you specifically want to re-use the same open connection – the connection pool does a much better job of handling connection re-use when your logic allows for the connection being reset, and you don't need any particular state associated with it. You also need to keep in mind the problems that using the same connection can cause – for example, only one command executing at a time if MARS is not on.
Disclaimer: This posting is provided "AS IS" with no warranties, and confers no rights
Updated: Fixed a glaringly simple bug in the Dispose() method.
namespace WebApplication3 { using System; using System.Collections.Generic; using System.Data; using System.Data.Common;
// Allows almost-automated re-use of connections across multiple call levels // while still controlling connection lifetimes. Multiple connections are supported within a single scope. // To use: // Create a new connection scope object in a using statement at the level within which you // want to scope connections. // Use Current.AddConnection() and Current.GetConnection() to store/retrieve specific connections based on your // own keys. // Simpler alternative: Use Current.GetOpenConnection(factory, connection string) where you need to use the connection // // Example of simple case: // void TopLevel() { // using (DbConnectionScope scope = new DbConnectionScope()) { // // Code that eventually calls LowerLevel a couple of times. // // The first time LowerLevel is called, it will allocate and open the connection // // Subsequent calls will use the already-opened connection, INCLUDING running in the same // // System.Transactions transaction without using DTC (assuming only one connection string)! // } // } // // void LowerLevel() { // string connectionString = <...get connection string from config or somewhere...>; // SqlCommand cmd = new SqlCommand("Some TSQL code"); // cmd.Connection = (SqlConnection) DbConnectionScope.Current.GetOpenConnection(SqlClientFactory.Instance, connectionString); // ... finish setting up command and execute it // }
/// /// Class to assist in managing connection lifetimes inside scopes on a particular thread. /// sealed public class DbConnectionScope : IDisposable { #region class fields [ThreadStatic()] private static DbConnectionScope __currentScope = null; // Scope that is currently active on this thread private static Object __nullKey = new Object(); // used to allow null as a key #endregion
#region instance fields private DbConnectionScope _priorScope; // previous scope in stack of scopes on this thread private Dictionary
public class PC {
/**
* 题目:生产者-消费者。
* 同步访问一个数组Integer[10],生产者不断地往数组放入整数1000,数组满时等待;消费者不断地将数组里面的数置零,数组空时等待。
*/
private static final Integer[] val=new Integer[10];
private static
在oracle连接(join)中使用using关键字
34. View the Exhibit and examine the structure of the ORDERS and ORDER_ITEMS tables.
Evaluate the following SQL statement:
SELECT oi.order_id, product_id, order_date
FRO
If i select like this:
SELECT id FROM users WHERE id IN(3,4,8,1);
This by default will select users in this order
1,3,4,8,
I would like to select them in the same order that i put IN() values so:
$(document).ready(
function() {
var flag = true;
$('#changeform').submit(function() {
var projectScValNull = true;
var s ="";
var parent_id = $("#parent_id").v
Mac 在国外很受欢迎,尤其是在 设计/web开发/IT 人员圈子里。普通用户喜欢 Mac 可以理解,毕竟 Mac 设计美观,简单好用,没有病毒。那么为什么专业人士也对 Mac 情有独钟呢?从个人使用经验来看我想有下面几个原因:
1、Mac OS X 是基于 Unix 的
这一点太重要了,尤其是对开发人员,至少对于我来说很重要,这意味着Unix 下一堆好用的工具都可以随手捡到。如果你是个 wi