Azure配置设置(cscfg),回退到Settings.Setting文件

时间:2015-05-08 21:12:23

标签: c# .net azure configuration settings

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

,这是一种痛苦

1 个答案:

答案 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);
}