One way to reduce repetitive code is through the usage of the template method pattern.
In your template method:
- Establish a connection
- Execute database operation (this is the customizable step)
- Close the connection
private async Task<T> GetAsync<T>(Func<IDbConnection, Task<T>> databaseOperation)
{
using IDbConnection myConnection = new SnowflakeDbConnection(connectionString: _connectionString);
myConnection.Open();
return await databaseOperation(myConnection).ConfigureAwait(false);
}
Then you can rewrite your publicly exposed methods:
public async Task<IEnumerable<T>> GetAllAsync<T>(string selectSqlCommand)
=> await GetAsync(conn => conn.QueryAsync<T>(selectSqlCommand));
public async Task<T> GetSingleOrDefaultById<T>(string sqlCommand, int id)
=> await GetAsync(conn => conn.QuerySingleOrDefaultAsync<T>(sqlCommand, new { id }));