Why doesn't Dapper dot net open and close the connection?

Dapper implicitly expects the connection to be open when it is used. Why doesn't he open and close it himself? Isn't that just connection management?

I ask because the co-worker and I went back and forth about what was going on behind the scenes with the connection pool, and if there was any use to maintaining a connection between several teams or to open and close it for each team.

+19
sqlconnection connection-pooling dapper
Sep 27 '12 at 19:47
source share
3 answers

Now Dapper (and for quite some time) has been doing this internally. It just works β„’




Original (outdated) answer:

You are not mistaken. The reason I didn’t notice that this inconvenience is because for obsolete reasons (in particular: we used LINQ-to-SQL exclusively), our main connection information is DataContext , so we re-expose the methods dapper as extension methods on a DataContext .

Stupid thing: what do these methods do:

 using(db.Connection.EnsureOpen()) { db.Connection.{the dapper method} } 

Here, EnsureOpen is a cheeky method that:

  • if the connection is open, returns null
  • Otherwise, it opens the connection and returns an IDisposable token, which closes the connection when completed

So: we obviously felt exactly your pain, but we realized it even further.

Please register this as a feature request. We have all the code (although I need to tweak it a bit to fit the β€œreader” for unbuffered data) - there is absolutely no reason dapper cannot own it.

+28
Sep 27 '12 at 20:01
source share

I should add the opposite answer here, or at least suggest that Dapper can handle connections differently, if only in certain circumstances. I just thought about Dapper.SqlMapper and there are checks in the ExecuteCommand method (Execute (public api) is called) to check if the connection is closed and then it opens if it is not.

I come across this since a code review by my colleague emphasized that I did not call an explicit call to connection.open before calling through dapper in the database. This was not perceived, since my integration tests were green, everything was inconvenient during operation. Thus, we plunged into the Dapper code. It can be argued that it is better to call it open for explanation, but, conversely, some may argue that the smaller the code, the better.

+3
Apr 02 '14 at 11:26
source share

I believe that Dapper does not manage your connections, as it is not part of its responsibilities as an ORM carpper. Dapper does not know whether you will reuse the same connection later - therefore, it accepts the connection as one of the parameters. The same thing applies to transactions - this is the application that should manage it, not ORM-mapper.

It is trivial to write your own extension methods that control the connection.

0
Sep 27 '12 at 19:56
source share



All Articles