在 Azure ServiceConfiguration ( .cscfg
) 中定义配置设置非常引人注目,因为我可以在 Azure 门户中更改该值。
但是,as discussed here Microsoft.WindowsAzure.CloudConfigurationManager.GetSettings("Foo")
将回退到寻找 <appSettings>
app.config 中的值。
是否可以将其回退到 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"
字符串参数
最佳答案
我最终为上述方法创建了一个新的重载,并能够从表达式中提取设置的名称:
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);
}
关于c# - Azure 配置设置 (cscfg) 并回退到 Settings.Setting 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30132927/