Unable read App.config values from Class Library

This may be the simple question to answer, but I am struggling to resolve.

I have Web.config with the following values in my Web Application.

<appSettings>
    <add key ="FirstName" value ="Prasad"/>
    <add key ="LastName" value ="Kanaparthi"/>
</appSettings>

I have App.config with following value in my Class Library (Say Lib).

<appSettings>
    <add key ="FullName" value ="Prasad Kanaparthi"/>
</appSettings>

The class library(Lib) is pluggable component, I have added the Class Library(Lib) reference in my Web Application.

I have the below code in my Class Library(Lib). When i create instance for GetAppSettings in my web application i can see below responses.

namespace Lib
{
    public class GetAppSettings
    {
        public GetAppSettings()
        {
            var FirstName = ConfigurationManager.AppSettings["FirstName"];  // O/P : Prasad
            var MiddleName = ConfigurationManager.AppSettings["LastName"];  // O/P : Kanaparthi

            var FullName = ConfigurationManager.AppSettings["FullName"];    // O/P : null
        }
    }
}

The Question is how can i read FullName from App.config which is Class Library (Lib).

Note: Since my Lib is pluggable component, So the consumers can change the FullName of their own. I cannot merge values to Web.confing from App.config.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You have to merge both configuration sections and place all settings in the main configuration file of your application. In case of the web applciation it would be the web.config.

Method 2

The short answer is: you can’t. The application using your library won’t pay any attention to your app.config. You could use a settings file instead or perhaps go a longer way around, abstract out the configuration manager and have it programmatically read your app.config as an XML file in the application’s output directory in order to include its settings. Understandably, neither option is ideal.

Method 3

While I don’t work often with web applications, in my desktop application I often face a similar issue. I’ve been using the code provided by Daniel Hilgarth https://stackoverflow.com/a/6151688/2212458 to temporarily switch configuration files. The plugin loader can pull in the plugin configuration file and then restore its own.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x