【问题标题】:Azure Configuration Settings (cscfg) with fallback to a Settings.Setting file回退到 Settings.Setting 文件的 Azure 配置设置 (cscfg)
【发布时间】:2015-07-19 21:45:36
【问题描述】:

在 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" 字符串参数

【问题讨论】:

  • falls back 已经到 web.config 和 app.config 了。您是否尝试在不签入 cscfg 中的连接字符串的情况下实施 ALM 方案?
  • @OgnyanDimitrov - 基本上,我只是不想在我的应用程序中使用“魔术”字符串来加载配置设置。我想要设置文件中的强类型和编译常量。
  • 绝对 - 没有魔法字符串 - 是要走的路。我制作了两个这样的模板 - 一个用于console,一个用于azure 应用程序使用Castle Dictionary Adapter

标签: c# .net azure configuration settings


【解决方案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);
}

【讨论】:

  • 哇,太好了!正是我想要的。
猜你喜欢
  • 2012-02-21
  • 1970-01-01
  • 2014-05-19
  • 2021-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-11
  • 2023-03-10
相关资源
最近更新 更多