c# - Azure 配置设置 (cscfg) 并回退到 Settings.Setting 文件

标签 c# .net azure configuration settings

在 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/

相关文章:

c# - 从 Task.Continuewith 更新 UI 标签

c# - WPF ComboBox : Trouble converting back-and-forth of Selected Item (Works in all cases, 但就是这个。)

具有 Office 365 身份验证的 Spring Boot 应用程序

azure - 错误: We don't have a valid access azure with Azure CLI

mysql - 从 Spring Boot 连接到 Azure MySQL 数据库时出错

c# - 围绕中心 vector2 点旋转对象

c# - 将数据从 form2 传递到 form1 并将其保存在字符串变量中

c# - 如何将 Github 库导入我的项目?

c# - 有没有办法使用币安 API 获取代币的市值或市值排名?

c# - 对象摘要中的换行符