是否可以将AzureAppConfiguration与Azure Function ServiceBusTrigger一起使用

时间:2019-07-09 11:51:07

标签: azure azure-functions azureservicebus azure-app-configuration

今天,我有一个带有ServiceBusTrigger的Azure函数,该函数从我的设置文件中读取值。像这样:

[FunctionName("BookingEventListner")]
public static async Task Run([ServiceBusTrigger("%topic_name%", "%subscription_name%", Connection = "BookingservicesTopicEndpoint")]Microsoft.Azure.ServiceBus.Message mySbMsg, ILogger log)
{

但是我在此解决方案中将Azure App Configuration与其他项目一起使用,并且还希望将终结点,主题和下标名称也存储到Azure App Configuration中(很好地添加它们不是问题,但检索它们则是问题)。

是否有某种方式可以将AzureAppConfiguration提供程序添加到配置处理程序中,就像我可以在Web应用程序中所做的那样?

webHostBuilder.ConfigureAppConfiguration((context, config) =>
{
    var configuration = config.Build();
    config.AddAzureAppConfiguration(options =>
    {
        var azureConnectionString = configuration[TRS.Shared.AspNetCore.Constants.CONFIGURATION_KEY_AZURECONFIGURATION_CONNECTIONSTRING];

        if (string.IsNullOrWhiteSpace(azureConnectionString)
                || !azureConnectionString.StartsWith("Endpoint=https://"))
            throw new InvalidOperationException($"Missing/wrong configuration value for key '{Constants.CONFIGURATION_KEY_AZURECONFIGURATION_CONNECTIONSTRING}'.");

        options.Connect(azureConnectionString);
    });
});

最佳问候 马格努斯

2 个答案:

答案 0 :(得分:2)

您可以使用ServiceBusTriggerAttribute来实现。

首先,使用AddAzureAppConfiguration获取端点,主题和下标名称。

var builder = new ConfigurationBuilder();
builder.AddAzureAppConfiguration(Environment.GetEnvironmentVariable("ConnectionString"));
var config = builder.Build();
string message = config["TestApp:Settings:Message"];

然后使用ServiceBusTriggerAttribute获取主题名称并订阅bind属性。

var attributes = new Attribute[]
{
    new ServiceBusAccountAttribute("yourservicebusname"),
    new ServiceBusTriggerAttribute(topic,sub)
};
var outputSbMessage = await binder.BindAsync<IAsyncCollector<BrokeredMessage>>(attributes);

答案 1 :(得分:0)

我在这里找到了有用的链接:http://marcelegger.net/azure-functions-v2-keyvault-and-iconfiguration#more-45

这对我有帮助,这就是我的方法。首先,我为IWebJobsBuilder接口创建了一个扩展方法。

   /// <summary>
    /// Set up a connection to AzureAppConfiguration
    /// </summary>
    /// <param name="webHostBuilder"></param>
    /// <param name="azureAppConfigurationConnectionString"></param>
    /// <returns></returns>
    public static IWebJobsBuilder AddAzureConfiguration(this IWebJobsBuilder webJobsBuilder)
    {
        //-- Get current configuration
        var configBuilder = new ConfigurationBuilder();
        var descriptor = webJobsBuilder.Services.FirstOrDefault(d => d.ServiceType == typeof(IConfiguration));
        if (descriptor?.ImplementationInstance is IConfigurationRoot configuration)
            configBuilder.AddConfiguration(configuration);

        var config = configBuilder.Build();

        //-- Add Azure Configuration
        configBuilder.AddAzureAppConfiguration(options =>
        {
            var azureConnectionString = config[TRS.Shared.Constants.CONFIGURATION.KEY_AZURECONFIGURATION_CONNECTIONSTRING];

            if (string.IsNullOrWhiteSpace(azureConnectionString)
                    || !azureConnectionString.StartsWith("Endpoint=https://"))
                throw new InvalidOperationException($"Missing/wrong configuration value for key '{TRS.Shared.Constants.CONFIGURATION.KEY_AZURECONFIGURATION_CONNECTIONSTRING}'.");

            options.Connect(azureConnectionString);
        });
        //build the config again so it has the key vault provider
        config = configBuilder.Build();

        //replace the existing config with the new one
        webJobsBuilder.Services.Replace(ServiceDescriptor.Singleton(typeof(IConfiguration), config));
        return webJobsBuilder;
    }

从appsetting.json中读取azureConnectionString的位置,其中应包含Azure应用程序配置的URL。

完成此操作后,我们需要在Azure Func项目中创建一个“启动”类,看起来像这样。

   public class Startup : IWebJobsStartup
    {
        //-- Constructor
        public Startup() { }

        //-- Methods
        public void Configure(IWebJobsBuilder builder)
        {
            //-- Adds a reference to our Azure App Configuration so we can store our variables there instead of in the local settings file.
            builder.AddAzureConfiguration(); 
            ConfigureServices(builder.Services)
                .BuildServiceProvider(true);
        }
        private IServiceCollection ConfigureServices(IServiceCollection services)
        {
            services.AddLogging();
            return services;
        }
    }

现在我可以在func类中从Azure应用程序配置中提取值,就像在appsetting.json文件中写入值一样。

[FunctionName("FUNCTION_NAME")]
public async Task Run([ServiceBusTrigger("%KEYNAME_FOR_TOPIC%", "%KEYNAME_FOR_SUBSCRIPTION%", Connection = "KEY_NAME_FOR_SERVICEBUS_ENDPOINT")]Microsoft.Azure.ServiceBus.Message mySbMsg
    , ILogger log)
{
    log.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg.MessageId}");
}