【问题标题】:clear singleton pattern concept please请明确单例模式概念
【发布时间】:2010-09-02 09:45:48
【问题描述】:

我想与 sql server DB 建立连接并保持单例模式。那么这个功能是内置在 dot net 中的吗?还是我们必须手动为这种情况编写代码?

【问题讨论】:

  • 使用单例模式的原因是什么?您是否担心一次打开太多连接?我问是因为也许你根本不需要它。
  • 通常的方式不是使用单例,而是使用连接池。这里的好处是连接池是在 .NET 中构建的,并且开箱即用。

标签: .net singleton


【解决方案1】:

一个延迟加载的单例示例

public sealed class Singleton

{ 单例() { }

public static Singleton Instance
{
    get
    {
        return Nested.instance;
    }
}

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

    internal static readonly Singleton instance = new Singleton();
}

}

【讨论】:

    【解决方案2】:

    使用sqlHelper 类将为您工作,这与数据库连接有关

    【讨论】:

    • @Lalit - sqlhelper 包含所有静态方法,因此无需担心对象创建它在内部管理 sqlconnection
    【解决方案3】:

    here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多