如何为 Web 作业处理提供基于配置的队列名称?

How to have a configuration based queue name for web job processing?

我有一个 webjob 应用程序来处理 ServiceBus 队列,它运行良好,使用以下方法:

public static void ProcessQueueMessage([ServiceBusTrigger("myQueueName")] BrokeredMessage message, TextWriter log)

但是,我希望能够在不重新编译的情况下更改队列名称,例如根据配置应用程序设置,可以吗?

是的,你可以做到。您可以实现自己的 INameResolver 并将其设置为 JobHostConfiguration.NameResolver。然后,您可以在我们的 ServiceBusTrigger 属性中使用类似 %myqueue% 的队列名称 - 运行时将调用您的 INameResolver 来解析该 %myqeuue% 变量 - 您可以使用任何您想要的自定义代码解析名称。您可以从应用程序设置等中读取它。

我使用 azure-webjobs-sdk-samples 中的配置设置找到了 INameResolver 的实现。

/// <summary>
/// Resolves %name% variables in attribute values from the config file.
/// </summary>
public class ConfigNameResolver : INameResolver
{
    /// <summary>
    /// Resolve a %name% to a value from the confi file. Resolution is not recursive.
    /// </summary>
    /// <param name="name">The name to resolve (without the %... %)</param>
    /// <returns>
    /// The value to which the name resolves, if the name is supported; otherwise throw an <see cref="InvalidOperationException"/>.
    /// </returns>
    /// <exception cref="InvalidOperationException"><paramref name="name"/>has not been found in the config file or its value is empty.</exception>
    public string Resolve(string name)
    {
        var resolvedName = CloudConfigurationManager.GetSetting(name);
        if (string.IsNullOrWhiteSpace(resolvedName))
        {
            throw new InvalidOperationException("Cannot resolve " + name);
        }

        return resolvedName;
    }
}