日期:2011-09-14  浏览次数:20384 次

非常有效的数据库/配置文件访问模型。成功使用在几万流量的网站上。任何建议欢迎大家交流。

在使用SqlCommand对象过程中,我们需要分配Connection对象。 通常,对于大型的Entity业务模型来说分配新的SqlConnection的操作非常频繁。要利用Pool的优化功能,就要想到保持Connection对象。由此想到可以把Connection和Transaction都保存到ConnectionProxy对象中。而此对象继承IDisposable仅仅存在于一个Request过程中。作为一个适用广泛的模型,我们建立ExecutionContext对象来封装对ConnectionProxy操作。

以下是ConnectionProxy代码:


    internal class ConnectionProxy : IDisposable
    ...{
        private string _connectionString = null;
        private SqlConnection _connection;
        private SqlTransaction _transaction;
        private int _tranCount = 0;

        /**//// <summary>
        /// Constructs a new ConnectionProxy instance, setting the connection string
        /// </summary>
        /// <param name="ConnectionString">A valid database connection string</param>
        internal ConnectionProxy(string connectionString)
        ...{
            _connectionString = connectionString;
        }

        /**//// <summary>
        /// Frees any connection related resources
        /// </summary>
        public void Dispose()
        ...{
            // ensure that the connection does not have a pending transaction
            if (_tranCount != 0)
            ...{
                // rollback the transaction stack until the rollback already occurs
                while (_tranCount > 0) this.RollbackTransaction();

                throw new DataAccessException("Dispose was called on a connection with a pending transaction. The transaction will be aborted.");
            }

            // close the connection if it is open
            if ((_connection != null) && (_connection.State == ConnectionState.Open))
            ...{
                _connection.Close();
            }

            _connection = null;
        }

        /**//// <summary>
        /// Gets the current connection object
        /// </summary>
        internal SqlConnection Connection
        ...{
            get
     &nbs