I have a web project (mvc) and data access layer in a separated class library project. I need to access to a connection string in app.config which sits in that library project.
ConfigurationManager.ConnectionStrings[0].ConnectionString pulls something strange. I don't have this kind of settings neither in the library's config nor in the web project's config files.
the App.config looks like that:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="DALConnectionString" connectionString="User ID=sa;Password=pass;Initial Catalog=db;Data Source=srv\SQL2005;" />
</connectionStrings>
</configuration>
To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].
Typically, the connection string will be stored in a configuration file somewhere within the application or web server. This connection string is typically stored in plain text to make it easy to edit and easy to change as the application is moved from development, to QA, to staging, and to production.
config string connectString = ConfigurationManager. ConnectionStrings["ConnectionString"]. ToString(); SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString); // Retrieve the DataSource property.
Connection strings in Visual Studio applications are often saved in the application configuration file (also referred to as application settings), or hard-coded directly in your application.
Your library should use dependency injection in this case for inversion of control.
Your class in the data access layer (DAL) library should take the connection string as a constructor argument
or a property value
.
This will make sure that your DAL can be used in other projects also and is not tied to your your mvc web application.
Let the code which will consume the DAL read the connection string from the config file and inject it into your class's constructor.
By default, a class library can't access a config file.
The client of the class library, in this case your web project, can provide config settings.
Therefore, put all the relevant settings, the connection strings, in the web's config file. The ConfigurationManager
code in the class library will use the web projects config settings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With