代码之家  ›  专栏  ›  技术社区  ›  Ewerton

自定义数据库连接对象:我应该使用通用的(单例)还是每个对象实例一个?

  •  0
  • Ewerton  · 技术社区  · 7 年前

    最佳实践是什么:只创建一个静态类(Singleton)来提供到数据库的所有必要连接,或者为每个DAO实例创建一个对象? 请注意,我的项目同时访问多个数据库,因此我创建了一个类 AcessoBanco 接收.INI配置文件的用户将返回所需的所有连接。 阿塞索班科 上课,但是,这真的是个好主意吗? 也许,如果我举一个例子

    使用单例方法

    public class Repository1
    {
        public Repository1(string iniFilePath)
        {
            AcessoBanco.Configure(iniFilePath); // Singleton that creates all the connections (concurrency excepction solved using locks)
    
            // After configured, just call AcessoBanco.GetConnections() in any point of the code to get the connections 
        }
    }
    

    public class Repository2
    {
        public AcessoBanco Conexoes { get; set; }
        public Repository2(string iniFilePath)
        {
            Conexoes = new AcessoBanco(iniFilePath); // Using one instance of AcessoBanco in each DAO. I will need to do it in every DAO.
        }
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Icarus    7 年前

    这样或类似的模式没有什么问题:

    using (var connection = new Connection()){
    
    }
    
        2
  •  0
  •   tlt    7 年前

    仅举两个例子:

    1. CosmosDB -建议使用客户机的单例实例,因为它使用(最常见的)http调用 HttpClient
    2. ADO.NET (对于sql server)-使用单实例是一个非常糟糕的主意,因为您的应用程序可能希望使用来自不同线程的连接,并且您将遇到一大堆不同的问题。这就是为什么它在引擎盖下使用连接池。