CloudStorageAccount の FromConfigurationSetting メソッドの注意点メモ

最近、ようやく Windows Azure 本番環境を試せるようになりました。そして、Development Storage との動作の違いに悪戦苦闘する日々。同じクラウドでも、Google App Engine のときはこんなに苦労しなかったのに。。。


…そろそろ本題に入ります。


Windows Azure Storage Services の Table や Blob を使うには、まず CloudStorageAccount を取得しなければいけません。本番環境で動かす際は、アカウントやキーを ServiceConfiguration.cscfg に記述すると思うので、下記のようなコードを書くことになります。

CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("接続文字列名");


この FromConfigurationSetting メソッドは、下記の例外が発生させることがあります。その内容がこちら。

SetConfigurationSettingPublisher needs to be called before FromConfigurationSetting can be used

FromConfigurationSetting メソッドを使う前に、SetConfigurationSettingPublisher メソッドを呼び出す必要があるんだそうです。でも、このメソッドの引数に何を渡せばいいのかサッパリ。


答えは Windows Azure SDK に同梱されているサンプルにありました。WebRole に下記のコードを記述すればいいんです。コードはサンプルから引用。

// This code sets up a handler to update CloudStorageAccount instances when their corresponding
// configuration settings change in the service configuration file.
CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
{
    // Provide the configSetter with the initial value
    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));

    RoleEnvironment.Changed += (sender, arg) =>
    {
        if (arg.Changes.OfType<RoleEnvironmentConfigurationSettingChange>()
            .Any((change) => (change.ConfigurationSettingName == configName)))
        {
            // The corresponding configuration setting has changed, propagate the value
            if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))
            {
                // In this case, the change to the storage account credentials in the
                // service configuration is significant enough that the role needs to be
                // recycled in order to use the latest settings. (for example, the 
                // endpoint has changed)
                RoleEnvironment.RequestRecycle();
            }
        }
    };
});

これでようやく、 FromConfigurationSetting メソッドを使って CludStorageAccount を取得できます。


必ず必要なコードなら、最初から WebRole に記述しておいて欲しいですね。不要になるのが一番ですけど。