简体   繁体   中英

SQLConnection instances dispose via Dapper

I am using ASP.NET web forms unity for DI in my project:

Next, I have installed Dapper in my project to call database resources via my DAL. In my Startup class I have plugged IDbConnection like this so that the Dapper can make use of that IDbConnection everywhere:

 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:

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. How and when will the SQLConnection be disposed after calling the database calls. There is no using written any where in the above code.

Will Dapper dispose the SQLConnection after making the call? If no, then can you share how to convert the above code to dispose the SQL Connection after making dapper call?

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

container.RegisterFactory<IDbConnection>(f => new SqlConnection(connectionString));

Then you can use that to get a new connection and place it in a using block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM