I replace this common statement:
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
// Do work here; connection closed on following line.
}
With this connection manager class that I made:
public class ConnectionBase : IConnectionBase
{
private static readonly string ConnString =
ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
private static readonly Lazy<MySqlConnection> ConnectionString =
new Lazy<MySqlConnection>(() => new MySqlConnection(ConnString));
private IDbConnection _db;
public IDbConnection Db
{
get
{
if (_db != null) return _db;
_db = ConnectionString.Value;
if (_db.State == ConnectionState.Closed) _db.Open();
return _db;
}
}
public void Dispose()
{
if (_db != null)
_db.Dispose();
}
}
And wired up to my repository like this:
public abstract class BaseRepository
{
protected readonly IDbConnection _repository;
public BaseRepository(IConnectionBase connection)
{
_repository = connection.Db;
}
}
Then I use it on top of the dapper
method (since it contains connection.close()
at the end of every method that it used).
public class MyTableRepository : BaseRepository
{
public MyTableRepository(IConnectionBase connection) : base(connection) {}
public List<MyTable> GetAllMyTable()
{
return _repository.Query("SELECT * FROM MyTable").ToList();
}
}
It's been working great thus far for quite some time in production.
Are there any side effects for this implementation since it doesn't explicitly state to dispose the IDbConnection
object?