2

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

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

但我在此解决方案中将 Azure 应用程序配置与其他项目一起使用,并希望将端点、主题和下标名也存储到 Azure 应用程序配置中(添加它们不是问题,但检索它们是)。

有没有办法将 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);
    });
});

最好的问候马格努斯

4

2 回答 2

2

我在这里找到了一个有用的链接: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}");
}
于 2019-07-18T06:30:46.530 回答
1

您可以使用ServiceBusTriggerAttribute来实现它。

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

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

然后使用ServiceBusTriggerAttributeto 获取主题和订阅的名称来绑定属性。

var attributes = new Attribute[]
{
    new ServiceBusAccountAttribute("yourservicebusname"),
    new ServiceBusTriggerAttribute(topic,sub)
};
var outputSbMessage = await binder.BindAsync<IAsyncCollector<BrokeredMessage>>(attributes);
于 2019-07-10T08:04:02.783 回答