Morgeh
Morgeh

Reputation: 679

WCF Services Configuration: How can I access the AppSettings in code using C#

I have googled around and just found reams of pages about how to set up a WCF service config which isn't what I want lol.

Basically, I have a factory class within my service which reads a Custom property from the config file to determine which Data Access Object to create, however, whenever I try to test it I get a NullReferenceException.

Here is the code:

    public string Config { get; set; }

    public ProjectFactory()
    {
        Config = ConfigurationManager.AppSettings["ProjectDAOConfig"].ToString();
        LoadDAO();
    }

And here is the custom property in the We.config file for the service:

<configuration>
    <configSections>
         //Sections removed to make it tidier
    </configSections>
   <appSettings>
       <add key="ProjectDAOConfig" value="stub"/>
   </appSettings>
   <connectionStrings/>

any why this doesn't work? Is the property in the wrong config file? If so should I create a App.Config file as currently there isnt on??

EDIT: I have used this same method on a asp.net website and it worked fine.

Upvotes: 3

Views: 9681

Answers (1)

Shiraz Bhaiji
Shiraz Bhaiji

Reputation: 65461

If you run the code from a web site it will read from the web.config.

If you run the code directly it will use the app.config in the project where the code starts running. For example if you run it from a unit test, then it is the app.config of the unit test project.

Upvotes: 6

Related Questions