以下是我正在处理的应用程序的当前存储库连接模式。
public class Repository : IDisposable {
public IDbConnection SiteConnection {
get {
if (siteConnection == null) {
siteConnection = new SqlConnection(DataBaseConfig.SiteConnectionString);
siteConnection.Open();
}
return siteConnection;
}
}
public void Dispose() {
if (siteConnection != null) {
siteConnection.Dispose();
siteConnection = null;
}
}
}
然后存储库看起来像这样:
public class SomeRepository : Repository {
public IEnumerable<Object> GetSomeObjects() {
return SiteConnection.Query<Object>("select statement");
}
public IEnumerable<OtherObject> GetSomeOtherObjects() {
return SiteConnection.Query<OtherObject>("select statement");
}
}
据我所知,Dispose仅在页面加载结束时调用。没有使用任何交易。在过去,我的印象是你应该总是迟到并在SQL方面提前退出。
public IEnumerable<Object> GetObjects() {
using(sqlconnection conn = new sqlconnection(connString)) {
conn.Open();
//do something with the database
}
}
哪种方法更具弹性并充分利用连接池并使用最少量的数据库资源?
答案 0 :(得分:1)
查看有关连接池的this msdn explanation。尽快关闭连接会将其返回池中。我认为,类似讨论中提出的最佳建议是让ado.net做它最擅长的事情而不是试图超越它的汇集逻辑。如果你在反编译器中查看SqlConnection,那么有很多内容正在进行中。令人难以置信的是,现在你甚至可以close a connection,因为它是更大事务的一部分(使用Sql Server 2008)。
答案 1 :(得分:-2)
使用100-200连接附近的连接池进行中间加载的网站,因此只有200个用户可以无需等待即可执行SQL查询,通常您需要尽快关闭连接,否则其他用户将等待,同时释放池连接。 / p>
所以我通常使用msdn(http://msdn.microsoft.com/ru-ru/library/system.data.sqlclient.sqlconnection.aspx)中的代码示例到每个存储库方法中:
.. getSomethingFromDb(){
..
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Do work here; connection closed on following line.
}
..
}
我的想法是在Dispose
方法中关闭连接是不好的做法,因为我无法知道GC何时会执行Dispose
。在连接数量有限且用户数量较多的系统中,这种做法非常糟糕。