Having an open connection and passing it between classes are generally a bad idea.
Sure, opening a connection is quite a performance hit, but that's already taken care of by the connection pool by reusing already opened connections. A remark though: always wait as long as possible to call connection.Open()
, especially in multithreaded code since this will assign the connection to your method (wich will potentionally increase the needed amount of open connections to the database).
To make your classes as generic as possible, I would recommend having a base class exposing a method with IDbConnection, and your repositories will have a more generic implementation.
internal abstract class Repository
{
private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
protected IDbConnection GetConnection()
{
return new SqlConnection(ConnectionString);
}
}
public class MyRepository : Repository
{
public IEnumerable<object> Get()
{
using (var connection = GetConnection())
{
connection.Open();
...
}
}
}