1) 使用类中的方法设置连接
//controller
using(Connection conn = new Connection()){
conn.Open();
MyClass myclass = new MyClass();
myclass.setDbConnection(conn);
}
//MyClass in Model
class MyClass {
Connection conn;
public setDbConnection(conn){
this.conn = conn;
}
public updateTableA(){
//using this.conn;
}
public updateTableB(){
//using this.conn;
}
public updateTableC(){
//using this.conn;
}
}
2) 将连接作为参数传递给每个方法
//controller
using(Connection conn = new Connection()){
conn.Open();
MyClass myclass = new MyClass();
}
//MyClass in Model
class MyClass {
public updateTableA(Connection conn){
//using conn;
}
public updateTableB(Connection conn){
//using conn;
}
public updateTableC(Connection conn){
//using conn;
}
}
哪个是正确(或更好)的方式?为什么?