通过单例类获得数据库连接 [英] getting db connection through singleton class

查看:300
本文介绍了通过单例类获得数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个单例类,这个类返回一个数据库连接。所以我的问题是这样的连接也满足单身人士的标准?

。如果不,比我怎样才能让它在单。

这里是代码。

 公共密封类SingletonDB 
{
静态只读SingletonDB实例=新SingletonDB();
静态的SqlConnection CON =新的SqlConnection(ConfigurationManager.ConnectionStrings [MYDB]的ConnectionString);

//显式静态构造函数来告诉C#编译器
//没有标记类型beforefieldinit
静态SingletonDB()
{
}

SingletonDB()
{
}

公共静态SingletonDB实例
{
得到
{
返回实例;
}
}

公共静态的SqlConnection GetDBConnection()
{
返回CON;
}
}


解决方案

您单尚客<​​/ p>

至于Singleton模式的推移,请参阅乔恩斯基特的非常好,详细的描述在这里:的http://www.yoda.arachsys.com/csharp/singleton.html



使用一个Singleton的SqlConnection对象是一个非常,非常糟糕的主意。没有任何理由任何做到这一点。



如果您正试图避免对性能的影响新的SqlConnection()或connection.Open()被告知真的有没有性能下降,因为连接池去幕后那里。连接池处理的昂贵连接的开/关。不SqlConnection对象。



您将无法打开多个SqlDataReaders /在同一时间连接命令和将运行到线程阻塞问题,如果你想分享多线程相同的连接对象。



单件模式是最在使用和滥用模式,有单身,你可能不是很多副作用意识到。很好谈单身的危险在这里 http://www.youtube.com/watch?v=-FRm3VPhseI


I have created an singleton class, this class returns a database connection. So my question is this connection is also satisfying singleton criteria?
If no, than how I can make it singleton.
Here is the code.

public sealed class SingletonDB
{
    static readonly SingletonDB instance = new SingletonDB();
    static SqlConnection con =new SqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ConnectionString);

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static SingletonDB()
    {
    }

    SingletonDB()
    {
    }

    public static SingletonDB Instance
    {
        get
        {
            return instance;
        }
    }

    public static SqlConnection GetDBConnection()
    {
        return con;
    }
}

解决方案

Your Singleton is still off.

As far as the singleton pattern goes, please see Jon Skeet's very good and detailed description here : http://www.yoda.arachsys.com/csharp/singleton.html

Using a Singleton for a SqlConnection object is a really, really bad idea. There is no reason to do this whatsoever.

If you are attempting to avoid a performance hit of "new SqlConnection()" or "connection.Open()" be advised that there really is no performance hit there because of the connection pooling going on behind the scenes. Connection Pooling handles the opening/closing of the expensive connections. Not the SqlConnection object.

You won't be able to open multiple SqlDataReaders/Commands with the connection at the same time and will run into thread blocking issues if you are trying to share the same connection object with multiple threads.

The Singleton pattern is the most over used and abused pattern and there are many side effects of the singleton that you may not be aware of. Very good talk about the dangers of singletons here http://www.youtube.com/watch?v=-FRm3VPhseI

这篇关于通过单例类获得数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆