Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a connection string from within a library

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>
like image 526
iLemming Avatar asked Mar 07 '11 16:03

iLemming


People also ask

How do you read a connection string?

To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].

Where are connection strings stored?

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.

How do I find my connection string Server name?

config string connectString = ConfigurationManager. ConnectionStrings["ConnectionString"]. ToString(); SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString); // Retrieve the DataSource property.

Where is the connection string in Visual Studio?

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.


2 Answers

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.

like image 51
Unmesh Kondolikar Avatar answered Oct 05 '22 07:10

Unmesh Kondolikar


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.

like image 36
Joe Ratzer Avatar answered Oct 05 '22 07:10

Joe Ratzer