Is it possible to add string Connection within a class?

Asked

Viewed 394 times

0

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

How could I add the SQL connection so it stays inside the DLL? I want to pass the direct connection here without using web.config:

ConfigurationManager.ConnectionStrings["Conexao"].ConnectionString

I have it:

public Contexto()
{
    minhaConexao = new SqlConnection(ConfigurationManager.ConnectionStrings["Conexao"].ConnectionString);
    minhaConexao.Open();
}
  • You want to remove the use of ConfigurationManager.ConnectionStrings["Conexao"].ConnectionString. That?

  • yes, I want to add connection inside the class so it won’t be visible on the web.config

3 answers

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 doesn’t seem like a good idea, but without more details you can’t know.

If you are completely sure that the connection string will not change, I see no problem in doing so.

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

public Contexto()
{
    minhaConexao = new SqlConnection(StringConexao);
    minhaConexao.Open();
}

2

When you use:

ConfigurationManager.ConnectionStrings["Conexao"].ConnectionString

Is using the active project configuration, ie the file .config connected to the application that is running.

Thus, besides being a bad practice to distribute a DLL with a file .config, the idea will not work, because this file will never be read.

Now, if you want to use file configuration Web.config 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();
}

1


You can use a string to insert the connection.. this would not be a good reason why 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;

  • Thanks! I prefer to recompile that leave open, same security issue.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.