Reputation: 12295
Defining a configuration setting in an Azure ServiceConfiguration (.cscfg
) is compelling because I can then change the value within the Azure portal.
However, as discussed here Microsoft.WindowsAzure.CloudConfigurationManager.GetSettings("Foo")
will fall back to looking for a <appSettings>
value in the app.config.
Is it possible to have it fallback to a Settings.setting
file instead?
I could create a method like this, but is there a better/built-in way?
public T GetSetting<T>(string name, T defaultValue = null)
{
return
!RoleEnvironment.IsAvailable
//we could be in a non azure emulated environment (ie unit test)
? defaultValue
: RoleEnvironemt.GetConfigurationSettingValue(name)
??
//in case no value is specified in .cscfg or <appSettings>
defaultValue;
}
And then have to call it like:
var settings = GetSetting("Example", Properties.Settings.Default.Example);
But this is a pain that I have to specify the "Example"
string parameter
Upvotes: 3
Views: 854
Reputation: 12295
I ended up creating a new overload for the method above and was able to pull out the name of the setting from an Expression:
var setting = __cloudSettingsProvider.GetSetting(
() => Properties.Setting.Default.ExampleConfiguration);
So now, I can pass in the setting name and default value. The method will check against Azure config
, then appSettings
, then applicationSettings
and then finally the hard coded default in Settings.Settings
.
Here's the code for the method (essentially):
public T GetSetting<T>(Expression<Func<T>> setting)
{
var memberExpression = (MemberExpression) setting.Body;
var settingName = memberExpression.Member.Name;
if (string.IsNullOrEmpty(settingName))
throw new Exception(
"Failed to get Setting Name " +
"(ie Property Name) from Expression");
var settingDefaultValue = setting.Compile().Invoke();
//Use the method posted in the answer to try and retrieve the
//setting from Azure / appSettings first, and fallback to
//defaultValue if no override was found
return GetSetting(
settingName,
settingDefaultValue);
}
Upvotes: 1