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
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"]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With