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

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

问题描述

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

如果没有,比我怎么可以使它单身一样。

这是代码。

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;
    }
}


推荐答案

单身人士还在休息。

就单身形象而言,请参见Jon Skeet的非常好的详细描述: http://www.yoda.arachsys.com/csharp/singleton.html

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

对于SqlConnection对象使用Singleton是一个非常糟糕的主意。没有理由这样做。

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

如果您尝试避免new SqlConnection()或connection.Open()的性能命中因为连接池在幕后,真的没有任何性能打击。连接池处理打开/关闭 昂贵的 连接。不是SqlConnection对象。

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.

您将无法同时使用连接打开多个SqlDataReaders / Commands,如果您正在尝试,将遇到线程阻塞问题与多个线程共享相同的连接对象。

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.

Singleton模式是最多使用和滥用的模式,单例中有许多副作用,您可能不会意识到。非常好的谈论单身人士的危险在这里 http://www.youtube.com/watch?v = -FRm3VPhseI

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天全站免登陆