Dapper,避免“connectionstring属性尚未初始化”错误

时间:2016-10-10 11:15:07

标签: c# asp.net-mvc dapper

当我尝试调用两个方法并且每个方法在数据库中执行查询时,我的应用程序出现问题。 这些方法使用using语句,因此在使用后会关闭连接。

我创建了一个DapperContext,我正在使用简单的注入器通过构造函数进行初始化:

public DapperContext(int idPortal)
{
    _connectionString = GetERPConnectionString(idPortal);
}

要打开连接并在数据库中执行查询,我创建了一个如下属性:

public IDbConnection DapperConnection
{
    get
    {
        if (_connection == null)
        {
            _connection = new SqlConnection(_connectionString);                    
        }

        if (_connection.State != ConnectionState.Open)
        {
            _connection.Open();
        }

        return _connection;
    }
}

这个DapperContext有一个Dispose方法,它关闭连接:

public void Dispose()
{
    if (_connection != null && _connection.State == ConnectionState.Open)
    {
        _connection.Close();
    }

    GC.SuppressFinalize(this);
}

在Repository类中,有一个方法将执行2个不同的Sqls,并且在它的方法中每个都指定了2个sql。 基本上,每个都初始化如下:

using (IDbConnection conexao = dapperContext.DapperConnection)
{
... runs a query
}

当我调用第一个方法时,查询运行得很好,但是当调用第二个方法时,在DapperConnection属性中,_connection.Open()中发生错误,因为_connectionString为空。

避免此错误的最佳方法是什么?我知道因为Dispose方法而丢失了connectionString,但由于我正在使用SimpleInjector来创建我的实例,这是通过请求完成的,我只会在另一个请求中再次使用此connectionString。

1 个答案:

答案 0 :(得分:2)

using (IDbConnection conexao = dapperContext.DapperConnection)
{
}
// -> conexao.Dispose() called on bound out, and _connection.Close(); is closed. 

" _connection"的结果关闭连接状态,无需重复使用。所以,如果你想保持这个代码的工作原理,那么Dispose方法应该是这样的:

public void Dispose()
{
    if (_connection != null && _connection.State == ConnectionState.Open)
    {
        _connection.Close();
        _connection = null;
    }
}