通过singleton类获取数据库连接

Sha*_*que 17 c# singleton design-patterns

我创建了一个单例类,这个类返回一个数据库连接.所以我的问题是这种联系也满足单身标准?
如果不是,我怎么能让它成为单身人士.
这是代码.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Cha*_*ant 29

你的单身人士仍在休息.

就单身人士模式而言,请参阅Jon Skeet的非常好的详细描述:http://www.yoda.arachsys.com/csharp/singleton.html

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

如果您试图避免"new SqlConnection()"或"connection.Open()"的性能损失,请注意由于连接池在幕后进行,因此确实没有性能损失.连接池处理昂贵连接的打开/关闭.不是SqlConnection对象.

您将无法同时使用该连接打开多个SqlDataReaders/Commands,并且如果您尝试与多个线程共享同一连接对象,则会遇到线程阻塞问题.

Singleton模式是最常用和滥用的模式,你可能没有意识到单身人士的许多副作用.很高兴在这里谈谈单身人士的危险http://www.youtube.com/watch?v=-FRm3VPhseI

  • 关于单例模式的 [更新的 Jon Skeet 文章](http://csharpindepth.com/Articles/General/Singleton.aspx) 的链接可以派上用场。 (2认同)

小智 5

在.NET C#中,您可以像这样写单身

    public class Singleton{
public static readonly Singleton Instance= new Singleton();
private Singleton(){}
Run Code Online (Sandbox Code Playgroud)

或用于多线程环境:

using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}
Run Code Online (Sandbox Code Playgroud)