C
C#3y ago
AK sanTari

.NET CORE 6 - Injecting IDbConnection... is it good practice?

I have an api to build and using dapper - IDbConnection. Atm i have an instance of IDbConnection for every db call and i dispose it immediately:
public async Task<IEnumerable<T>> LoadData<T>(
string sqlQuery,
string connectionId)
{
using IDbConnection dbConnection = new SqlConnection(_configuration.GetConnectionString(connectionId));

return await dbConnection.QueryAsync<T>(sqlQuery);
}
public async Task<IEnumerable<T>> LoadData<T>(
string sqlQuery,
string connectionId)
{
using IDbConnection dbConnection = new SqlConnection(_configuration.GetConnectionString(connectionId));

return await dbConnection.QueryAsync<T>(sqlQuery);
}
Since i only have one sql database to query, is it good practice to inject the dbConnection on startup? Will this cause any performance issue since the connection will stay open all the time (if i'm correct)?
3 Replies
Cutter
Cutter3y ago
i do not see a problem with this
AK sanTari
AK sanTariOP3y ago
noice, thanks gave it a try all seem to be good
Cisien
Cisien3y ago
I would probably inject a connection factory, or connection pool But i often deal with multiple databases
Want results from more Discord servers?
Add your server