在ASP.NET网站中使用单例连接是一个好主意

Jea*_*ôté 5 asp.net singleton dbconnection

我目前在我的Web应用程序上使用单例,因此始终只有一个连接到数据库.

我想知道这是不是一个好主意,因为我现在遇到了这个错误:

超时已过期.从池中获取连接之前经过的超时时间.这可能是因为所有池连接都在使用中并且达到了最大池大小.

另一个重要的一点是,我的网站目前处于开发阶段,并没有很多人继续使用它,所以我不明白为什么我会收到此错误!

这是我的单身人士的代码:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

/// <summary>
/// This class take care of all the interaction with the database
/// </summary>
public class DatabaseFacade
{
    SqlConnection m_conn = null;

    string m_csLanguageColumn;

    //Variables that implement the Singleton pattern
    //Singleton pattern create only one instance of the class
    static DatabaseFacade instance = null;
    static readonly object padlock = new object();

    /// <summary>
    /// Private constructor. We must use Instance to use this class
    /// </summary>
    private DatabaseFacade()
    {
    }

    /// <summary>
    /// Static method to implement the Singleton
    /// </summary>
    public static DatabaseFacade Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new DatabaseFacade();
                }
                return instance;
            }
        }
    }

    /// <summary>
    /// Do the connection to the database
    /// </summary>
    public void InitConnection(int nLanguage)
    {
        m_conn = new SqlConnection(GetGoodConnectionString());

        try
        {
            //We check if the connection is not already open
            if (m_conn.State != ConnectionState.Open)
            {
                m_conn.Open();
            }

            m_csLanguageColumn = Tools.GetTranslationColumn(nLanguage);

        }
        catch (Exception err)
        {
            throw err;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

Jef*_*nal 23

使用单个连接是一个非常糟糕的主意 - 如果正确锁定对连接的访问​​,则意味着ASP.NET一次只能为一个用户提供服务,这将严重限制应用程序的增长能力.

如果连接没有正确锁定,事情会变得非常奇怪.例如,一个线程可能会在另一个线程尝试对其执行命令时处置该连接.

您应该只在需要时创建新的连接对象,而不是使用单个连接,以利用连接池.

连接池是SqlClient类(可能还有其他数据提供者)的默认行为.当您使用连接池时,无论何时"创建"连接,实际上都会从现有连接池中提取连接,这样您就不会每次都从头开始构建连接.当您释放它(关闭它或丢弃它)时,您将它返回到连接池,使您的连接总数相对较低.


编辑:如果您没有关闭(或处置)您的连接,您将看到您提到的错误(从池中获取连接之前经过的超时时间).确保在使用完每个连接后立即执行此操作.

有几个很好的堆栈溢出问题可以讨论这个问题,我怀疑它可能会有所帮助!

  • 虽然我同意单例是SqlConnection的一个坏主意,但我没有看到任何迹象表明它仅限于单个请求.代码中没有锁定可以阻止SqlConnection对象的多个用户(如果有的话,由于线程问题,这会让它变得更糟糕). (2认同)

Noo*_*ilk 7

不,这是个坏主意.您使用连接池.

  • 解释会很好. (3认同)