Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 Application Settings

Tags:

c#

asp.net-mvc

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

like image 414
Callum Linington Avatar asked Dec 14 '22 20:12

Callum Linington


2 Answers

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"]
like image 161
Anthony Shaw Avatar answered Jan 03 '23 21:01

Anthony Shaw


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
like image 22
xDaevax Avatar answered Jan 03 '23 19:01

xDaevax