IOptions 值未在 Azure Function 应用程序中绑定

问题描述 投票:0回答:1

我有一个 .net 8 隔离功能应用程序。

我正在注入

IOptions<TelegramSettings>
,但是
settings.Value.Token
始终是空的。谁能告诉我为什么?

// Settings class
public class TelegramSettings
{
    public const string ConfigKey = "Telegram";

    [MinLength(1)]
    public string Token { get; set; } = "";
}
// Program.cs
var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(services =>
    {
        services.AddApplicationInsightsTelemetryWorkerService();
        services.ConfigureFunctionsApplicationInsights();
        services.AddOptions<AuthSettings>(AuthSettings.ConfigKey);
        services.AddSingleton<ITelegramService, TelegramService>();
    }; //etc
// Consuming service
public class TelegramService : ITelegramService
{
    private readonly TelegramBotClient TelegramBotClient;

    public TelegramService(IOptions<TelegramSettings> telegramOptions)
    {
        TelegramBotClient = new TelegramBotClient(telegramOptions.Value.Token);
    }
}
{
  "version": "2.0",
  "Telegram": {
    "Token": "sf"
  }, etc
}
c# configuration azure-functions
1个回答
0
投票

您应该使用

Configure
方法来注册
TelegramSettings
客户端。

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices((hostBuilder, services) =>
    {
        //NOTE THIS
        services.Configure<TelegramSettings>(a => hostBuilder.Configuration.GetSection("Telegram").Bind(a));

        services.AddApplicationInsightsTelemetryWorkerService();
        services.ConfigureFunctionsApplicationInsights();
        services.AddOptions<AuthSettings>(AuthSettings.ConfigKey);
        services.AddSingleton<ITelegramService, TelegramService>();
    });
© www.soinside.com 2019 - 2024. All rights reserved.