Callum Linington
Callum Linington

Reputation: 14417

MVC 5 Application Settings

So I want to store some settings in the application, ones that I can only read from (which i think is pretty much the idea).

How do I inject the reader, I'm not entirely sure how to read application settings in the first place or whether it already has an interface to inject.

I would either want something like this:

public interface IPropertyService
{
    string ReadProperty(string key);
}

and then implement:

public class DefaultPropertyService : IPropertyService
{
    public string ReadProperty(string key)
    {
        // what ever code that needs to go here
        // to call the application settings reader etc.

        return ApplicationSetting[key];
    }
}

Any help on this subject would be great

Upvotes: 4

Views: 16609

Answers (2)

xDaevax
xDaevax

Reputation: 2022

You have the right idea, and you're basically there. For the web, configuration settings are stored in the Web.Config, under the AppSettings node. You can access those in code by using ConfigurationManager.AppSettings. Here is a sample implementation of an injectable service that accesses the config.

public interface IPropertyService {

    string ReadProperty(string key);

    bool HasProperty(string key);

} // end interface IPropertyService

public class WebConfigurationPropertyService : IPropertyService {

    public WebConfigurationPropertyService() {

    } // end constructor

    public virtual bool HasProperty(string key) {
        return !String.IsNullOrWhiteSpace(key) && ConfigurationManager.AppSettings.AllKeys.Select((string x) => x).Contains(key);
    } // end method HasProperty

    public virtual string ReadProperty(string key) {
        string returnValue = String.Empty;
        if(this.HasProperty(key)) {
            returnValue = ConfigurationManager.AppSettings[key];
        } // end if
        return returnValue;
    } // end method ReadProperty

} // end class WebconfigurationPropertyService

Upvotes: 3

Anthony Shaw
Anthony Shaw

Reputation: 8166

Where are you trying to store your application settings? Does the appSettings section of the Web.Config not suffice?

<appSettings>
  <add key="someSetting" value="SomeValue"/>
</appSettings>

and then read your setting this way

ConfigurationManager.AppSettings["someSetting"]

Upvotes: 9

Related Questions