Is it necessary to close connection once query is executed explicitly calling Close method or putting the connection within Using statement? Would leaving connection open lead to connection reuse and improve SQL performance for future queries?
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- Generic Generics in Managed C++
- How to Debug/Register a Permanent WMI Event Which
I am assuming that you are using latest version of Dapper.
With Dapper, there are two ways to manage connection:
Fully manage yourself: Here, you are fully responsible for opening and closing connection. This is just like how you treat connection while working with ADO.NET.
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. This is similar to
DataAdapter.Fill()
method.I personally do not recommend this way.This may not be applicable every time. Following is what Marc Gravell says in one of the comment for this answer: https://stackoverflow.com/a/12629170/5779732Ofcourse, you can call multiple queries on single connection. But, connection should be closed (by calling
Close()
,Dispose()
method or by enclosing it inusing
block) to avoid resource leak. Closing connection returns it to connection pool. Involvement of connection pool improves the performance over new connection cost.In addition to just handling connection, I suggest you implement UnitOfWork to manage transactions as well. Refer this excellent sample on GitHub.
Following source code may help you. Note that this is written for my needs; so it may not work for you as is.
Now, your repositories should accept this UnitOfWork in some way. I choose Dependency Injection with Constructor.
And then you call it like this:
With transaction:
Without Transaction:
This way, instead of directly exposing connection in your calling code, you control it at one location.
More details about Repository in above code could be found here.
Please note that
UnitOfWork
is more than just a transaction. This code handles only transaction though. You may extend this code to cover additional roles.