Question

Here is the current repository connection pattern on an app I am working on.

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;
  }
}



}

The repositories then look like this:

public class SomeRepository : Repository {

   public IEnumerable<Object> GetSomeObjects() {
        return SiteConnection.Query<Object>("select statement");
    }

   public IEnumerable<OtherObject> GetSomeOtherObjects() {
        return SiteConnection.Query<OtherObject>("select statement");
    }

}

From what I can tell, Dispose is only called at the very end of the page load. No transactions are being used. In the past, I was under the impression you should always get in late and get out early when it comes to SQL.

public IEnumerable<Object> GetObjects() {
    using(sqlconnection conn = new sqlconnection(connString)) {
        conn.Open();
        //do something with the database
    }
}

Which method is more bulletproof and takes full advantage of connection pooling and uses the least amount of database resources?

Was it helpful?

Solution

Have a look at this msdn explanation about connection pooling. Closing the connection as soon as possible returns it to the pool. I think the best advice that has come out of similar discussions is to let ado.net do what it does best and not try to outhink its pooling logic. If you look at SqlConnection in a decompiler, there is a lot going on under the covers. It's incredible how now you can even close a connection while it is part of a larger transaction (with Sql Server 2008).

OTHER TIPS

Website with middle load using connection pool near 100-200 connections, so only 200 users can execute SQL queries without waiting and usually you need close connections as quickly as possible or other users will wait, when pool connections will be released.

So I usually use code sample from msdn(http://msdn.microsoft.com/ru-ru/library/system.data.sqlclient.sqlconnection.aspx) into each repository method:

.. getSomethingFromDb(){
..
     using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        // Do work here; connection closed on following line.
    }
..
}

As my mind is bad practise to close connection in Dispose method, because I can't know when GC will execute Dispose. And in systems with a limited number of connections and big number of users this way is very very bad practise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top