The way I normally structure applications is to have all the database access in one DLL (module for other languages). All the data access methods take a connection string as a parameter (in the case of EF its a bit different but still gets passed in based on the connection string in the app.config or web.config of the primary application).
This way the DAL (Data Access Layer) knows about the structure of the database but does not know any connection details. It means you can swap out the connection string at run time to connect to DEV, UAT, or PROD. The basic structure of a DAL method would look like this:
Public SomeType GetData(string connectionString)
{
try
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("", sqlConnection))
{
sqlConnection.Open();
cmd.CommantText = "SomeSqlHere";
SomeType returnVal = //Code to get your data and map to your return type
return returnVal;
}
}
catch (Exception ex)
{
Log.Error("Caught error.", ex);
throw;
}
}
The internals would be a bit different for EF but overall using Dependency Injection saves having to hard code connection strings in various places.
As to how to inject the connection string I normally have a Configuration class that reads and sometimes caches the config values. This configuration has taken many forms and evolved depending on the needs of the specific application I am working on. The call to a data method would look like GetDate(Config.GetConnectionString())
. Then only one place in the application needs to know what the connection string is and every where else it gets passed.