我有一个 .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
}
您应该使用
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>();
});