DOWper与UOW - 不要关闭连接

时间:2017-06-16 13:57:04

标签: repository-pattern dapper unit-of-work

我已经使用以下artical

在Dapper中实现了我的DAL

Dapper Implementation

但它创建了与db的每个数据库调用的连接。它不重用连接池。我相信我已经关闭并正确处理了连接。

这是如何从服务层调用的示例

dtoList = unitofWork.RegionalSettingRepository.GetCurrencySymbols(); unitofWork.Commit(); // To close the connections

这是存储库调用

public List<CurrencySymbolDTO> GetCurrencySymbols()
    {
        List<CurrencySymbolDTO> dtoList = null;
        try
        {
            string strSQL = "SELECT * from CurrencySymbol";
            dtoList = this.Connection.Query<CurrencySymbolDTO>(strSQL, null, transaction: Transaction).ToList();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {

        }
        return dtoList;
    }

有人可以告诉我为什么要为每个数据库调用创建大量连接。 我确实使用以下SQL查询来监视连接数

SELECT DB_NAME(dbid) as DBName, COUNT(dbid) as NumberOfConnections, loginame as LoginName FROM sys.sysprocesses WHERE DB_NAME(dbid) ='database name' GROUP BY dbid, loginame

提前致谢

1 个答案:

答案 0 :(得分:0)

您提到的文章非常适合用Dapper学习UoW;我自己开始用那篇文章研究UoW。在实现它以满足我的业务需求时我遇到了类似的问题,并且我对代码进行了一些修改。您可以在this回答中找到详细的代码。

使用此代码,您可以更好地控制连接/事务;你这样称呼它:

使用交易:

@SuppressWarnings("unchecked")
@Component
public class EntityEventListenerRegistry {

    @Autowired
    private SessionFactory sessionFactory;

    /**
     * EventListenerRegistry:http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#annotations-jpa-entitylisteners
     */
    @PostConstruct
    public void registerListeners(){
        EventListenerRegistry eventListenerRegistry = ((SessionFactoryImplementor) sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);
        eventListenerRegistry.prependListeners(EventType.PRE_INSERT, EntityListener.class);
        eventListenerRegistry.prependListeners(EventType.PRE_UPDATE, EntityListener.class);
    }

}

没有交易:

using(DalSession dalSession = new DalSession())
{
    UnitOfWork unitOfWork = dalSession.UnitOfWork;
    unitOfWork.Begin();
    try
    {
        //Your database code here
        unitOfWork.Commit();
    }
    catch
    {
        unitOfWork.Rollback();
        throw;
    }
}
相关问题