How to access the connection string from the library

I have a web project (mvc) and data access level in a separate class library project. I need to access the connection string in app.config, which is in this library project.

ConfigurationManager.ConnectionStrings [0] .ConnectionString is pulling something strange. I have no such settings either in the library configuration or in the configuration files of the web project.

App.config is as follows:

<?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> 
+4
source share
4 answers

By default, the class library cannot access the configuration file.

The class library client, in this case your web project, can provide configuration settings.

Therefore, put all the relevant settings, connection strings, in the web configuration file. The ConfigurationManager code in the class library will use the web project configuration settings.

+5
source

Your library should use dependency injection in this case to invert control .

Your class in the data access layer (DAL) library should take a connection string as a constructor argument or property value .

This will ensure that your DAL can also be used in other projects and is not tied to your mvc web application.

Let the code that will use DAL read the connection string from the configuration file and enter it into your class constructor.

+5
source

you must add the snippet shown above in web.config and then at run time the configuration manager will use it even if it is running inside your class library.

0
source

You cannot access app.config for a DLL.

app.config only works for the entry point site or web.config for the web project.

Try to copy the connection to the entry point configuration or load the configuration by analyzing the XML configuration - not recommended.

0
source

Source: https://habr.com/ru/post/1342664/


All Articles