refactoringdapperdbconnection

How to refactor repeating IDbConnection.open\close?


maybe its stupid question, but I confused my self. I use Dapper with Autofac (DI) and in my business layer I always use the following construction:

db.Open(); //db is IDbConnection instance
db.InsertOrDeleteOrUpdate(...)
db.Close();

whether a good solution to hide db.Open() and db.Close() by delegate method? For example:

dbHelper.do(db => db.InsertOrDeleteOrUpdate(...));

What do you do in such cases?


Solution

  • Redundant code is not the only issue in this code. Your code is hitting the database for every action. This will hit the performance if your DBServer is deployed on remote machine. Refer this answer.

    Have you ever come across UnitOfWork pattern? It is very good solution for handling connections on some higher level.

    Connection Factory is another good alternative and it can be used with UnitOfWork. But I personally prefer only UnitOfWork.

    Refer this answer for sample code of UnitOfWork.

    Once you choose from above, it is easy to reduce the redundancy by using "connection per request" pattern. You need to identify centralized location in your code where to create DalSession and where to dispose it.