我正在使用 .NET 7 預覽版,我將一個秘密存盤為環境變數,并嘗試將其分配給我正在注入的類IOptions。
我將其他非秘密引數存盤在appsettings.json:
"MyServerName": {
"EnvironmentName": "MyServerName",
"EndpointAddress": "net.tcp://MyServerName:8201/Services/"
}
我的配置系結類是這樣的:
public class MyEnvironment
{
public string EnvironmentName { get; set; }
public string EndpointAddress { get; set; }
public string AzureAuthRelayConStr { get; set; }
public string AzureStorageConnectionStr { get; set; }
}
在我的Program.cs:
var MyEnvironment = new MyEnvironment();
builder.Configuration.GetSection(machineName).Bind(MyEnvironment);
// Here is the problem. This doesn't persist. I know I can add this to the constructor, but what's the proper
// method of making changes before binding?
MyEnvironment.AzureStorageConnectionStr = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
builder.Services.Configure<MyEnvironment>(builder.Configuration.GetSection(machineName));
倒數第二行是我要解決的問題,但它不會持續存在。我意識到我可能可以將這些其他引數添加到建構式中,但我的問題是在系結之前修改它們的正確方法是什么,或者有可能嗎?
有沒有辦法在不使用 JSON 宣告自定義類的情況下傳遞一個List或IOptions只是一些通用引數?
uj5u.com熱心網友回復:
你可以使用這個:
builder.Services.Configure<MyEnvironment>(options =>
{
builder.Configuration.GetSection(machineName).Bind(options);
options.AzureStorageConnectionStr = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/524385.html
標籤:C#网asp.net 核心依赖注入
