0
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 several banks and so I created a class AcessoBanco
which, from a file .INI
creates the necessary connections.
My project was using a static class (Singleton) that returned the bank connections I need. I started to have sporadic exceptions because my system is multi-threaded. I decided to create Locks for exclusive access to the properties that expose the connections, however, I was in doubt, this is a good practice.
I imagine that if each DAO created its own instance of the connections, this competition problem would be eliminated. I’ll give you 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.
}
}
About opening connection and closing connection for the shortest period of time, I understand this and use this good practice. About pools, I also understand and know how it works.My problem is different. In my case, the system connects in a variable number of databases and I need to find out which are these databases from a .ini. file Anyway I understood what you wanted to explain.
– Ewerton
Then I don’t understand what you want in the question.
– Maniero
Imagine this: I will have repositories that access data from more than one database, for example:
SELECT * from Banco1.dbo.Tabela1 INNER JOIN Banco2.dbo.Tabela1
. Note that in my repository class, I need access to the Banco1 and Banco2 connection. Currently they are in this Singleton that I spoke and I access so: Meusingleton.Get connected1(); Meusingleton.Get connected1(); got it? That’s the only reason I created a Singleton. So all repositories access the same Singleton. My question is whether this is good practice or there’s a better way to do it.– Ewerton
Other words: it’s good practice to expose these connections I need in Singleton and let the repositories access the connections they need or pass the connections to the repository (for example by a constructor).
– Ewerton