这里我在抽象类
中使用连接状态 public abstract class Connection
{
private static string _Connection = ConfigurationManager.ConnectionStrings["CTXDB"].ConnectionString;
public static string GetConnection{ get { return _Connection; }}
}
public abstract void ProcessConnection();
这个类我在另一个类(BusinessConnection.cs)中实现
public class BusinessClass :Connection
{
public override void ProcessConnection()
{
using (var conn = new SqlConnection(Connection.GetConnection))
{
conn.Open();
}
}
现在我在我的控制器中调用了这个类(BusinessConnection.cs)
BusinessClass objcon = new BusinessClass();
public IHttpActionResult Index()
objcon.ProcessConnection();
SqlCommand cmd = new SqlCommand("select * from Employee");
//Here how can i inject my Connection in cmd
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows == true)
答案 0 :(得分:2)
似乎有一点点设计缺陷。您显然希望使用BusinessClass
/ Connection
类之外的连接。
所以也许你可以这样做:
public abstract class Connection
{
public abstract SqlConnection OpenConnection();
// your code
}
和您的BusinessClass
:
public override SqlConnection OpenConnection()
{
var conn = new SqlConnection(Connection.GetConnection))
conn.Open();
return conn;
}
然后在你的查询代码中:
using(SqlConnection conn = objcon.OpenConnection())
{
// create SqlCommand and pass conn!
using(SqlCommand cmd = new SqlCommand("select * from Employee", conn))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// and the rest of your rdr reading code
}
}
}
using
语句负责关闭/处理相应的对象。