C#SQL连接池

时间:2018-07-09 11:38:40

标签: c# sql-server asp.net-mvc

大家好,

我遇到一个特殊的问题,我的C#应用​​程序的连接池中的空间不足。我编写了一个自定义SqlHelper类,该类应返回每个类要使用的相同连接。

但是这似乎没有按预期工作。调试时,除非已关闭连接,否则似乎返回了相同的连接。我以为我要实例化SqlHelper类的多个实例,并将其更改为使用一个会话变量,该变量为每个类返回相同的SqlHelper实例。

在此方面将提供任何帮助,因为我无法理解为什么它无法按预期工作。

下面是我的SqlHelper类:

public class SqlHelper {

    /// <summary>
    /// Private connection string which reads the connection string from the web.config file
    /// </summary>
    private string _connectionString {
        get {
            //Get the connection string from the web.config
            return ConfigurationManager.ConnectionStrings["defaultConn"].ConnectionString;
        }
    }

    /// <summary>
    /// Internal connection
    /// </summary>
    private SqlConnection _connection;
    /// <summary>
    /// Public connection that instantiates the connection
    /// </summary>
    public SqlConnection Connection {
        get {
            //Check if the connection has not been created
            if (_connection == null)
                _connection = new SqlConnection(_connectionString);
            //Check if the connection is closed, if it is, open it back up again
            if (_connection.State == ConnectionState.Closed || _connection.State == ConnectionState.Broken)
                _connection.Open();
            //Return the connection
            return _connection;
        }
    }

    /// <summary>
    /// Executes SQL query with(out) parameters which will return a SqlDataReader to access results
    /// </summary>
    /// <param name="sqlCommand"></param>
    /// <param name="para"></param>
    /// <returns>SqlDataReader filled with results</returns>
    public SqlDataReader GetSqlReader(string sqlCommand, SqlParameter[] para = null) {
        //Build up the command with the connection
        SqlCommand command = new SqlCommand(sqlCommand, Connection);
        //Add all the parameters to the sql command
        if (para != null)
            foreach (SqlParameter param in para)
                command.Parameters.Add(param);
        return command.ExecuteReader();
    }

下面是我的BaseController,它为每个会话返回相同的SqlHelper实例:

public class BaseController : Controller
{
    //protected SqlHelper sqlHelper = new SqlHelper();

    protected SqlHelper sqlHelper {
        get {
            SqlHelper helper = Session["SqlHelper"] as SqlHelper;
            if (helper == null) {
                helper = new SqlHelper();
                Session["SqlHelper"] = helper;
            }
            return helper;
        }
    }

1 个答案:

答案 0 :(得分:1)

在将_connection对象保留为字段的情况下,使您的类变为Disposable。