Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigurationManager.AppSettings getting null?

I did not realize that: 'have a web.config in a separate class library and' was reading the web.config app setting from different web application.

I am using VS2010 target framework 3.5

I don't know what is wrong here but I am getting null when I try to get ConfigurationManager.AppSettings["StoreId"];

private string _storeid = GetStoreId;  public static string GetStoreId {     get     {         return ConfigurationManager.AppSettings["StoreId"];     } } 

web.config:

<appSettings>     <add key="StoreId" value="123" /> </appSettings> 
like image 302
Nick Kahn Avatar asked Nov 25 '10 21:11

Nick Kahn


People also ask

What is ConfigurationManager appSettings?

it is a .net builtin mechanism to define some settings before the application starts, without recompiling. see msdn configurationmanager.

Does ConfigurationManager work in .NET core?

ConfigurationManager was added to support ASP.NET Core's new WebApplication model, used for simplifying the ASP.NET Core startup code.

Why appSettings keys in web config are not case sensitive?

Why appsettings keys (in web. config) are not case sensitive ? The default comparer is a CaseInsensitiveComparer that uses the conventions of the invariant culture; that is, key comparisons are case-insensitive by default.


2 Answers

If you are UNIT TESTING you need A COPY of the APP.CONFIG inside the UNIT TEST PROJECT

like image 135
Ben Avatar answered Sep 22 '22 11:09

Ben


Problem

The usual cause for this is due to context.

Cause

When you have a solution with two projects, if the App/Web.Config is in the main project it wont work if the context of the running application is the second project such as a library, unit test, etc.

Conundrum

To read values from the config in other projects (with System.Configuration) you'll need to move/copy the config file to the project with the running context. Unfortunately duplicating files defeats the tenants of good programming; OOP, Source Code Management, SOLID, etc.

Cool Solution

A nifty solution is adding config file shortcuts in other projects so you only update one file:

enter image description here

It would be nice to divide the contents of config files across project's. Elegantly, like Sharing Assembly Files as per answer #2: https://stackoverflow.com/a/15319582/495455 but alas it's by context

like image 26
Jeremy Thompson Avatar answered Sep 25 '22 11:09

Jeremy Thompson