Dapper implicitly expects a connection to be open when it uses it. Why doesn't it open and close it itself? Wouldn't this simply connection management?
I ask because a co-worker and I have been going back and forth on the nature of what goes on behind the scenes with connection pooling, and if there is any benefit to keeping a connection open amongst multiple commands, or to open and close it for each command.
Allow Dapper to manage it: Dapper automatically opens the connection (if it was not opened) and closes it (if it was opened by Dapper) for you.
Dapper provide two ways to handle connection. First is - Allow Dapper to handle it. Here, you do not need to open the connection before sending it to Dapper. If input connection is not in Open state, Dapper will open it - Dapper will do the actions - Dapper will close the connection.
We are not adhering to the connection pooling. But the reality is, as we discussed earlier, Dapper is a mapping library. So it will not maintain the connection management. It's extended the ADO.NET feature for connection management.
Dapper now (and for quite some time) deals with this internally. It just works™
Original (outdated) answer:
You aren't wrong. The reason I hadn't noticed this inconvenience is that for legacy reasons (specifically: we used to use LINQ-to-SQL exclusively) our primary connection-like-thing is a DataContext
- so we re-expose the dapper methods as extension methods on DataContext
.
The silly thing is: what these methods do is:
using(db.Connection.EnsureOpen()) { db.Connection.{the dapper method} }
Here EnsureOpen is a cheeky method that:
So: we obviously felt exactly your pain, but we implemented it a layer further up.
Please log this as a feature request. We have all the code (although I'll need to tweak it slightly to fit the "reader" for non-buffered data) - there's absolutely no reason that dapper can't take ownership of this.
I have to add a contrary answer here, or at least suggest that Dapper may handle connections differently, if only in certain circumstances. I have just reflected over Dapper.SqlMapper and there are checks in the ExecuteCommand Method (called out to by Execute (on the public api)) to check if a connection is closed and then it opens it, if it isn't.
I come across this as a code review by my colleague highlighted that I wasn't explicitly calling a connection.open before calling out via dapper to the DB. This wasn't picked up as my integration tests were all green, everything was hunky-dory at runtime. So we dived into the Dapper code. It could be argued its better to call open for explicitness, but conversely some may argue that the less code the better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With