【发布时间】:2019-04-26 09:28:18
【问题描述】:
最佳实践是什么:只创建一个静态类(Singleton)来提供所有需要的数据库连接,或者为每个 DAO 实例创建一个对象?
请注意,我的项目同时访问多个数据库,因此我创建了一个类AcessoBanco,它接收一个 .INI 配置文件 e 返回我需要的所有连接。
我使用的是单个静态类方法,但由于系统执行一些多线程任务,我收到了关于并发的零星异常。我通过在AcessoBanco 类中创建锁来解决它,但是,这真的是个好主意吗?
也许,如果我为每个 dao 对象放置一个 AcessoBanco 实例,并发问题可以更优雅地解决,对吗?一些例子:
使用单例方法
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.
}
}
【问题讨论】:
标签: c# repository-pattern dao data-access-layer data-access