Search code examples
c#mysql.net.net-coredapper

Best way to do connection management in dapper?


I am using the following way of querying in dapper on a MySQL database.

using (var db = new MySqlConnection(ConfigurationHandler.GetSection<string>(StringConstants.ConnectionString)))
{
    resultSet = db.Execute(UpdateQuery, new { _val = terminalId }, commandType: CommandType.Text);
    db.Close();//should i call this or not
    db.Dispose();//should i call this or not
}

Is it a good way of explicitly calling db.close and db.dispose? My application could be handling 100's of requests per second.


Solution

  • A using block is a convenience arround the IDisposable interface. It ensures that the dispose method is called at the end of the block.

    See: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement.

    In your case you can remove the explicit calls to db.Close() and db.Dispose() because you are not re-using the connection object.

    using (var db = new MySqlConnection(ConfigurationHandler.GetSection<string>(StringConstants.ConnectionString)))
                    {
                        resultSet = db.Execute(UpdateQuery,
                            new { _val = terminalId }, commandType: CommandType.Text);
                    }
    

    The following link provides further details about .Close vs .Dispose: https://stackoverflow.com/a/61171/1028323