【问题标题】:Best way to do connection management in dapper?在 Dapper 中进行连接管理的最佳方法是什么?
【发布时间】:2020-01-18 00:48:00
【问题描述】:

我正在使用以下方式在 MySQL 数据库上的 dapper 中进行查询。

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
}

这是显式调用 db.close 和 db.dispose 的好方法吗?我的应用程序每秒可以处理 100 个请求。

【问题讨论】:

  • 您不需要CloseDisposeusing 已经为您调用 Dispose
  • resultSet的类型是什么?
  • resultSet 不同点不同

标签: c# mysql .net .net-core dapper


【解决方案1】:

using 块是围绕IDisposable 接口的便利。它确保在块的末尾调用 dispose 方法。

请参阅:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

在您的情况下,您可以删除对 db.Close() 和 db.Dispose() 的显式调用,因为您没有重新使用连接对象。

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

以下链接提供了有关 .Close 与 .Dispose 的更多详细信息:https://stackoverflow.com/a/61171/1028323

【讨论】:

  • 另外,如果您的数据库驱动程序(阅读:用于 mysql 的 nuget 包)支持连接池,那么这种做法将允许您的 app_pool 在一段时间内重新打开连接,而无需重新连接。 -- 既方便又高效。
  • 感谢亚历克斯和杰森。我正在这样做,池中有大约 100 个连接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 2014-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多