[英]SQLConnection instances dispose via Dapper
I am using ASP.NET web forms unity for DI in my project:我在我的项目中使用ASP.NET Web 表单统一进行 DI:
Next, I have installed Dapper in my project to call database resources via my DAL.接下来,我在我的项目中安装了Dapper ,通过我的 DAL 调用数据库资源。 In my Startup class I have plugged IDbConnection like this so that the Dapper can make use of that IDbConnection everywhere:
在我的 Startup 类中,我像这样插入了 IDbConnection,以便 Dapper 可以在任何地方使用该 IDbConnection:
container.RegisterInstance<IDbConnection>(new SqlConnection(connectionString));
My question here is that if I use the dbconnection like this in my class, how will the sql connection be diposed when the work is done:我这里的问题是,如果我在我的班级中使用这样的 dbconnection,那么工作完成后将如何处理 sql 连接:
public class MyProvider: IMyProvider
{
private readonly IDbConnection _dbConnection;
public MyProvider(IDbConnection dbConnection)
{
_dbConnection = dbConnection;
}
public async Task<IEnumerable<MyData>> GetMyData()
{
const string sql = @"SELECT * from mytable";
return await _dbConnection.QueryAsync<Content>(sql);
}
}
I am worried about this part "(new SqlConnection(connectionString))" in my start up while setting up the DI hooks.在设置 DI 挂钩时,我在启动时担心这部分“(new SqlConnection(connectionString))”。 How and when will the SQLConnection be disposed after calling the database calls.
调用数据库调用后如何以及何时处理 SQLConnection。 There is no using written any where in the above code.
在上面的代码中没有使用写任何地方。
Will Dapper dispose the SQLConnection after making the call?调用后Dapper会处理SQLConnection吗? If no, then can you share how to convert the above code to dispose the SQL Connection after making dapper call?
如果没有,那么您能否分享一下如何在进行dapper调用后将上述代码转换为配置SQL连接?
It won't be disposed, because the instance is effectively a Singleton, and is held for the lifetime of the application.它不会被释放,因为该实例实际上是一个单例,并且在应用程序的整个生命周期内都被保留。 This is not the correct way to inject a DB connection.
这不是注入数据库连接的正确方法。
Instead, you should register a factory method, using RegisterFactory
相反,您应该使用
RegisterFactory
注册一个工厂方法
container.RegisterFactory<IDbConnection>(f => new SqlConnection(connectionString));
Then you can use that to get a new connection and place it in a using
block.然后您可以使用它来获取新连接并将其放置在
using
块中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.