What is the best practice: to have only one point (Singleton) that returns the connections to the database or to create an instance of the connection for each object?
My system accesses multiple banks and so I created a AcessoBanco
class that, from a .INI
file, creates the necessary connections.
My project was using a static class (Singleton) that returned the database connections I need. I started having sporadic exceptions because my system is multi-thread . I have created locks for exclusive access to the properties that expose the connections, but I was in doubt, this is a good practice.
I imagine that if each DAO creates its own instance of the connections, this competition problem would be eliminated. I'll give some examples
Using a Singleton
public class Repositorio1
{
public Repositorio1(string caminhoArquivoINI)
{
AcessoBanco.Configurar(caminhoArquivoINI); // Singleton único que cria as conexões (gerava problemas de concorrencia resolvido com locks)
// Depois de configurado basta usar AcessoBanco.ObterConexao() em qualquer ponto do código para obter uma conexão
}
}
Using one instance per object
public class Repositorio2
{
public AcessoBanco Conexoes { get; set; }
public Repositorio2(string caminhoArquivoINI)
{
Conexoes = new AcessoBanco(caminhoArquivoINI); // Utilizando uma instancia por objeto. Isso tem que ser feito em toda classe que deseja acessar o banco.
}
}