将 IConfiguration 注入服务集合时环境变量为 null
Environment variables are null when injecting IConfiguration into service collection
我正在尝试将我的 azure 函数中的本地配置传递到另一个项目中的 iServiceCollection,该函数与之相关。
我在 .NET 6 中工作
这是我的函数 startup.cs 基于对这个
的回答
[assembly: FunctionsStartup(typeof(DatabaseInit.Startup))]
namespace Edos.DatabaseInit;
public class Startup:FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
var configuration = builder.GetContext().Configuration;
builder.Services.AddInfrastructure(configuration);
}
}
这是我的 local.settings.json
{
"IsEncrypted": false,
"ServiceBusConnectionString": "myconnectionstring",
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
我的函数
public class CosmosInit
{
private readonly IMessagingService _messagingService;
public CosmosInit(IMessagingService messagingService)
{
_messagingService = messagingService;
}
[FunctionName("CosmosInit")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
await _messagingService.PushToTopic("demotopic", "message");
return new OkObjectResult(responseMessage);
}
}
这是我的 Azure 函数的依赖项目中的 Above AddInfrastructure 方法
public static class DependencyInjection
{
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
var serviceBusConnectionString = Environment.GetEnvironmentVariable("ServiceBusConnectionString");
if (string.IsNullOrEmpty(serviceBusConnectionString))
{
throw new InvalidOperationException(
"Please specify a valid ServiceBusConnectionString in the Azure Functions Settings or your local.settings.json file.");
}
//using AMQP as transport
services.AddSingleton((s) => {
return new ServiceBusClient(serviceBusConnectionString, new ServiceBusClientOptions() { TransportType = ServiceBusTransportType.AmqpWebSockets });
});
services.AddScoped<IMessagingService, MessagingService>();
return services;
}
}
这就是我的方法(在基础设施项目中)
public class MessagingService: IMessagingService
{
private readonly ServiceBusClient _serviceBusClient;
public MessagingService(ServiceBusClient serviceBusClient)
{
_serviceBusClient = serviceBusClient;
}
// the sender used to publish messages to the topic
public async Task<int> PushToTopic(string topic, string serviceMessage)
{
var sender = _serviceBusClient.CreateSender(topic);
var message = new ServiceBusMessage(serviceMessage);
await sender.SendMessageAsync(message);
return 1;
}
}
但是执行的时候没有报错。但在基础设施项目中 Environment.GetEnvironmentVariable("ServiceBusConnectionString") 仅显示为空。我发现它没有从函数 local.settings.json
中获取任何配置
请指出我做错了什么或如何解决这个问题..拜托
根据评论,尝试查找或添加类似
的代码
using Microsoft.Extensions.Configuration;
Some class {
...
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json", optional: false)
.Build();
//just to verify
var conn = builder.GetSection("ServiceBusConnectionString").Get<string>();
Console.WriteLine(conn);
...
}
您可以将它添加到您当前的方法“Configure”中,并保持其余代码不变。
或者验证您是否有以前的配置加载点。
默认情况下,appsettings.json 等配置文件不会自动复制到函数应用程序的输出文件夹。更新您的 .csproj 文件以匹配以下示例以确保复制文件。
发件人:https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection
Some class {
...
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json", optional: false)
.AddEnvironmentVariables() //HERE!!
//just to verify
var conn = Environment.GetEnvironmentVariable("ServiceBusConnectionString");
Console.WriteLine(conn);
...
}
我正在尝试将我的 azure 函数中的本地配置传递到另一个项目中的 iServiceCollection,该函数与之相关。
我在 .NET 6 中工作
这是我的函数 startup.cs 基于对这个
[assembly: FunctionsStartup(typeof(DatabaseInit.Startup))]
namespace Edos.DatabaseInit;
public class Startup:FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
var configuration = builder.GetContext().Configuration;
builder.Services.AddInfrastructure(configuration);
}
}
这是我的 local.settings.json
{
"IsEncrypted": false,
"ServiceBusConnectionString": "myconnectionstring",
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
}
}
我的函数
public class CosmosInit
{
private readonly IMessagingService _messagingService;
public CosmosInit(IMessagingService messagingService)
{
_messagingService = messagingService;
}
[FunctionName("CosmosInit")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
await _messagingService.PushToTopic("demotopic", "message");
return new OkObjectResult(responseMessage);
}
}
这是我的 Azure 函数的依赖项目中的 Above AddInfrastructure 方法
public static class DependencyInjection
{
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
{
var serviceBusConnectionString = Environment.GetEnvironmentVariable("ServiceBusConnectionString");
if (string.IsNullOrEmpty(serviceBusConnectionString))
{
throw new InvalidOperationException(
"Please specify a valid ServiceBusConnectionString in the Azure Functions Settings or your local.settings.json file.");
}
//using AMQP as transport
services.AddSingleton((s) => {
return new ServiceBusClient(serviceBusConnectionString, new ServiceBusClientOptions() { TransportType = ServiceBusTransportType.AmqpWebSockets });
});
services.AddScoped<IMessagingService, MessagingService>();
return services;
}
}
这就是我的方法(在基础设施项目中)
public class MessagingService: IMessagingService
{
private readonly ServiceBusClient _serviceBusClient;
public MessagingService(ServiceBusClient serviceBusClient)
{
_serviceBusClient = serviceBusClient;
}
// the sender used to publish messages to the topic
public async Task<int> PushToTopic(string topic, string serviceMessage)
{
var sender = _serviceBusClient.CreateSender(topic);
var message = new ServiceBusMessage(serviceMessage);
await sender.SendMessageAsync(message);
return 1;
}
}
但是执行的时候没有报错。但在基础设施项目中 Environment.GetEnvironmentVariable("ServiceBusConnectionString") 仅显示为空。我发现它没有从函数 local.settings.json
中获取任何配置请指出我做错了什么或如何解决这个问题..拜托
根据评论,尝试查找或添加类似
的代码using Microsoft.Extensions.Configuration;
Some class {
...
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json", optional: false)
.Build();
//just to verify
var conn = builder.GetSection("ServiceBusConnectionString").Get<string>();
Console.WriteLine(conn);
...
}
您可以将它添加到您当前的方法“Configure”中,并保持其余代码不变。 或者验证您是否有以前的配置加载点。
默认情况下,appsettings.json 等配置文件不会自动复制到函数应用程序的输出文件夹。更新您的 .csproj 文件以匹配以下示例以确保复制文件。
发件人:https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection
Some class {
...
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("local.settings.json", optional: false)
.AddEnvironmentVariables() //HERE!!
//just to verify
var conn = Environment.GetEnvironmentVariable("ServiceBusConnectionString");
Console.WriteLine(conn);
...
}