Search code examples
c#sqlado.netdappersqlclient

When Should I Use connection.OpenAsync in Dapper?


I am using "Using" Statement like this:

using (SqlConnection connection = new(ApplicationSettingsData.ConnectionString)
{
    // connection.Query();
}

As I Searched and understand about the connection of dapper, it has 2 workarounds. one is automatic open/close of the connection by dapper, and the other is fully control by me.

what I understand is, If I have only one query, I should just use dapper methods and done! (Like the Code above) and if I have multiple queries and methods and works to do, I should Open connection myself and let it open until the last query I have, then close it (Like the Example Below).

Did I understand it correctly?

using (SqlConnection connection = new(ApplicationSettingsData.ConnectionString)
{
    await connection.OpenAsync();
    // QueryAsync<>...
    // Execute()...
    // QueryAsync<>...
    await connection.CloseAsync();
}

Solution

  • Yes you are correct.

    Dapper will automatically open and close the connection if needed. But if you are doing multiple queries and want to keep the conenction open in between then open it explicitly.

    Do note that because of connection pooling, the physical connection is not actually closed. It is returned to the pool, and if it is reused within a certain amount of time then it will just stay open and be reset on next usage. Because of this, you should not ever cache connection objects, as the connection pool handles the lifetime.

    Closing explicitly is not needed as the using does that.