简体   繁体   English

IDbConnection工厂使用Dapper

[英]IDbConnection factory using Dapper

I using dapper in my ASP.NET WebForms solution. 我在ASP.NET WebForms解决方案中使用dapper。

All my classes which handles data retrieves an open connection from this base class 我处理数据的所有类都从这个基类中检索一个打开的连接

public abstract class SalesDb : IDisposable
{
    protected static IDbConnection OpenConnection()
    {
        IDbConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SalesDb"].ConnectionString);
        connection.Open();
        return connection;
    }

    public void Dispose()
    {
        OpenConnection().Dispose();
    }
}

Example of a service class that uses this base class 使用此基类的服务类的示例

public class LeadService : SalesDb
{
    public IEnumerable<LeadDto> Select()
    {
        using (IDbConnection connection = OpenConnection())
        {
            return connection.Query<LeadDto>("Lead_Select",
                null, null, true, null, CommandType.StoredProcedure);
        }
    }
}

Is there any disadvantage that OpenConnection( ) method in the base class is static and return a new instance for every call? 基类中的OpenConnection( )方法是静态的并且为每个调用返回一个新实例是否有任何缺点?

You are creating a new connection in dispose? 您正在处置中创建新连接? That won't work! 那不行! Use a simple loop with more than 100 iterations( max pool size default is 100 ) and you'll probably see some kind of exceptions( too many open connections , ExecuteReader requires an open and available Connection etc.). 使用一个超过100次迭代的简单循环(默认最大池大小为100),您可能会看到某种异常( 开放连接太多ExecuteReader需要打开和可用的连接等)。

In any case i expect serious performance problems since the pool needs to create new physical connections consecutively. 在任何情况下,我都会遇到严重的性能问题,因为池需要连续创建新的物理连接。

I would not reinvent the Connection-Pool . 我不会重新发明连接池 My advice is: don't use that class, all the more in asp.net. 我的建议是:不要在asp.net中使用那个类。

Don't poach on the Connection-Pool's territory ;-) 不要在Connection-Pool的领土上偷猎 ;-)

But note that both of your questions can be answered with No . 请注意,你的两个问题都可以用No来回答。 The static method is not a problem(unlike a static connection) and also not that it always returns a new connection(since the pool would return connections that are currently not in use). 静态方法不是问题(与静态连接不同),也不是它总是返回一个新连接(因为池将返回当前未使用的连接)。 But the main problem of your class is the dispose which creates connections and opens them. 但是你的类的主要问题是dispose创建连接并打开它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM