How to access app.config value in class library?

I have a web application that uses class library dlls. I cannot access the app.config value in the class library

How am I trying to access app.config :

 ConfigurationSettings.AppSettings["conStr"].ToString(); 

this returns a null value

Also, when I try to use the ConfigurationManager , it says that no assembly link was found or missing.

using System.Configuration.

+4
source share
3 answers

You must put the value of AppSettings inside the web.config application because it overrides app.config from the class library.

Add a reference to the System.Configuration namespace in the class library project, they will receive the value that you expect from the web.config , and not from the app.config file.

+8
source

Add a reference to the System.Configuration library in your project, then enter your key as follows

 ConfigurationManager.AppSettings["conStr"] 

Note that the web application will look for the web.config , not the app.config !

+2
source

AMMS answer should work and start you up. But I like to tell ("tell, don't ask") my library, where they should connect. Instead of letting your library find this connection string, let the code provide it:

 var myLib = new MyLib(ConfigurationManager.AppSettings["conStr"]); 

So your configuration is in web.config / app.config / custom config / registry / .ini file, your library doesn't care.

0
source

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


All Articles