在Azure ServiceConfiguration(.cscfg
)中定义配置设置非常引人注目,因为我可以更改Azure门户中的值。
但是,as discussed here Microsoft.WindowsAzure.CloudConfigurationManager.GetSettings("Foo")
将回退到在app.config中查找<appSettings>
值。
是否可以让它回退到Settings.setting
文件?
我可以创建一个这样的方法,但是有更好的/内置方式吗?
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;
}
然后必须称之为:
var settings = GetSetting("Example", Properties.Settings.Default.Example);
但是,我必须指定"Example"
字符串参数
答案 0 :(得分:1)
我最终为上面的方法创建了一个新的重载,并且能够从表达式中提取设置的名称:
var setting = __cloudSettingsProvider.GetSetting(
() => Properties.Setting.Default.ExampleConfiguration);
现在,我可以传入设置名称和的默认值。该方法将检查Azure config
,然后检查appSettings
,然后检查applicationSettings
,最后检查Settings.Settings
中的硬编码默认值。
以下是该方法的代码(基本上):
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);
}