CloudConfigurationManager不从app.config中获取ApplicationSettings

时间:2012-07-23 11:13:58

标签: c# azure configuration-files

我有一个包含一些Azure帮助程序类的库。在这些帮助程序类中,我获取了Azure帐户名和密钥等设置。在Azure中运行时,这些设置将从云配置文件(cscfg)中获取。一切正常。

为了在Azure之外对这些类进行单元测试(特别是RoleEnvironment),我在单元测试项目中创建了相同变量名的设置。这些实际上保存在app.config文件中,并通过设置部分进行编辑,该部分位于我的测试项目的属性部分下。我没有创建自己的从web.config / app.config设置中抽象云配置设置的方法,而是决定使用CloudConfigurationManager类。但是,当我运行我的单元测试时,我的设置都没有被选中,所以我只是得到了空值。但是,如果我将app.config文件更改为使用下面“appSettings”格式的设置,那么我会获得有效值。这样做的缺点是我无法再使用visual studio中的设置编辑器页面编辑我的设置。

所以我的问题是我做错了什么,或者这是云配置管理器的限制,它只能选择手动添加的appSettings而不是使用编辑器添加的applicationSettings?

<appSettings>
    <add key="Foo" value="MySettingValue"/>
</appSettings>

以上作品,而以下不是:

<applicationSettings>
    <ComponentsTest.Properties.Settings>
      <setting name="Foo" serializeAs="String">
        <value>MySettingValue</value>
      </setting>
    </ComponentsTest.Properties.Settings>  
</applicationSettings>

1 个答案:

答案 0 :(得分:33)

CloudConfigurationManager仅支持web.config / app.config的 AppSettings 部分,如果Azure配置中缺少该设置,则会尝试从此处读取值。文档指出,如果属性RoleEnvironment.IsAvailable true (在Azure中运行)将不读取web.config / app.config,但是 >不正确,如下面的源代码所示(不检查IsAvailable)。

您可以查看source,看看会发生什么:

    /// <summary>
    /// Gets a setting with the given name.
    /// </summary>
    /// <param name="name">Setting name.</param>
    /// <returns>Setting value or null if such setting does not exist.</returns>
    internal string GetSetting(string name)
    {
        Debug.Assert(!string.IsNullOrEmpty(name));

        string value = null;

        value = GetValue("ServiceRuntime", name, GetServiceRuntimeSetting);
        if (value == null)
        {
            value = GetValue("ConfigurationManager", name, n => ConfigurationManager.AppSettings[n]);
        }

        return value;
    }

正如您所看到的,只有一次调用正常的 ConfigurationManager 类,只需访问 AppSettings

相关问题