Is it possible to add connection string within a class?

0

I have a project of type class library where I have my Context, in it I get the SQL connection that is in my web.config .

How can I add the SQL connection so that it stays inside the DLL? I want to pass the direct connection here, without having to use web.config:

ConfigurationManager.ConnectionStrings["Conexao"].ConnectionString

I have this:

public Contexto()
{
    minhaConexao = new SqlConnection(ConfigurationManager.ConnectionStrings["Conexao"].ConnectionString);
    minhaConexao.Open();
}
    
asked by anonymous 05.07.2016 / 21:19

3 answers

1

You can use a string to insert the connection .. this would not be good because to change the connection you would have to recompile the dll.

 minhaConexao = new SqlConnection("Server=myServerAddress;Database=myDataBase;UserId=myUsername;Password=myPassword;");
  

Server = myServerAddress; Database = myDataBase; User Id = myUsername;   Password = myPassword;

    
05.07.2016 / 21:31
2

You can pass the connection directly as a parameter of SqlConnection , after all the return of ConfigurationManager.ConnectionStrings["Conexao"] is a simple string. This does not seem like a good idea to me, but without further details I have no way of knowing.

If you have complete certainty that the connection string will not change, I see no problem doing so.

private const string StringConexao = @"Data Source=.\SQLEXPRESS;Initial Catalog=NomeBanco;Integrated Security=True"

public Contexto()
{
    minhaConexao = new SqlConnection(StringConexao);
    minhaConexao.Open();
}
    
05.07.2016 / 21:35
2

When you use:

ConfigurationManager.ConnectionStrings["Conexao"].ConnectionString

You are using the active project configuration, that is, the .config file attached to the application you are running.

So, apart from it being a bad practice to distribute a DLL with a .config file, the idea will not work, because this file will never be read.

Now, if you want to use the configuration of the Web.config file of the project that uses the DLL, you will have to make a little smarter logic. Something like:

public Contexto()
{
    String connectionString = "Sua connection string default aqui";
    if (ConfigurationManager.ConnectionStrings["Conexao"] != null)
    {
        connectionString = ConfigurationManager.ConnectionStrings["Conexao"].ConnectionString;
    }

    minhaConexao = new SqlConnection(connectionString);
    minhaConexao.Open();
}
    
05.07.2016 / 21:38