I am working on a project, while doing coding I got confused, as to where to initialize the connection in the constructor of the class or in the function I am using it.
My code in the constructor is as below:
public class clsTest
{
private readonly MySql.Data.MySqlClient.MySqlConnection _dbInstance;
public clsTest()
{
_dbInstance = new MySql.Data.MySqlClient.MySqlConnection(ClsConnectionString.connectionString);
}
public bool insert(object model)
{
using (_dbInstance)
{
//do what ever you want to achieve
return true;
}
}
}
and the second approach (i.e. in the function only) is:
public List<tEntity> Getts()
{
using (var db = new MySql.Data.MySqlClient.MySqlConnection(ClsConnectionString.connectionString))
{
// do whatever you want to do
}
}
Which approach is better?