今天开放 Windows Azure 存储服务的时候碰到一个问题:
执行下面的初始化存储代码
// read account configuration settings
var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
抛出异常
网上找了一些资料 没有收获 于是回去看Windows azure 白皮书中的示例描述,发现少了一段很重要的代码
这是我的代码
namespace WCFServiceWebRole
{
public class WebRole : RoleEntryPoint
{
public override bool OnStart()
{
DiagnosticMonitor.Start("DiagnosticsConnectionString");
// 有关处理配置更改的信息,
// 请参见 http://go.microsoft.com/fwlink/?LinkId=166357 上的 MSDN 主题。
RoleEnvironment.Changing += RoleEnvironmentChanging;
return base.OnStart();
}
private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
{
// 如果配置设置发生更改,
if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
{
// 请将 e.Cancel 设置为 true 以重新启动此角色实例
e.Cancel = true;
}
}
}
}
修改之后的代码
namespace WCFServiceWebRole
{
public class WebRole : RoleEntryPoint
{
public override bool OnStart()
{
DiagnosticMonitor.Start("DiagnosticsConnectionString");
// 有关处理配置更改的信息,
// 请参见 http://go.microsoft.com/fwlink/?LinkId=166357 上的 MSDN 主题。
RoleEnvironment.Changing += RoleEnvironmentChanging;
// 当使用配置文件中ConfigurationSettings时必须调用CloudStorageAccount.SetConfigurationSettingPublisher
// 来说明当配置文件在发布后被更改时将采取何种操作
Microsoft.WindowsAzure.CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
{
configSetter(Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue(configName));
RoleEnvironment.Changed += (sender, arg) =>
{
if (arg.Changes.OfType
()
.Any((change) => (change.ConfigurationSettingName == configName)))
{
if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))
{
RoleEnvironment.RequestRecycle();
}
}
};
return base.OnStart();
}
private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
{
// 如果配置设置发生更改,
if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
{
// 请将 e.Cancel 设置为 true 以重新启动此角色实例
e.Cancel = true;
}
}
}
}
原因就是少了这个方法SetConfigurationSettingPublisher,
vs2010建项目的时候该方法不会自动产生,导致后面云存储账户失败。
pos:目前云计算在windows azure国内刚起步,这方面的教程特别少 仅限于一般的入门级教程 碰到疑难问题最好google国外的技术资料