这是我正在处理的应用程序上的当前存储库连接模式。
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
}
}
哪种方法更具弹性并充分利用连接池并使用最少量的数据库资源?