我似乎找不到確切問題的解決方案,因為我需要在呼叫構建器之前呼叫依賴注入,但這會導致控制器類中的新物件實體化并且值丟失。如果我在系結后立即放置這一行,我會收到一條錯誤訊息,指出在構建服務后無法修改服務。
在舊版本的 .net 中,由于存在 Startup.cs,由于方法 ConfigureService 和 Configure 的分離,這似乎不是問題。
AuthenticationBind.cs
public class AuthenticationBind
{
public int AuthenticationId { get; set; }
public string AuthenticationName { get; set; }
}
應用設定.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"TestAuthenticationBind": {
"AuthenticationId": "1324556666",
"AuthenticationName": "Test Authentication Name"
},
"AllowedHosts": "*"
}
程式.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddSingleton<AuthenticationBind>();
var app = builder.Build();
AuthenticationBind tb = new AuthenticationBind();
IConfiguration configuration = app.Configuration;
configuration.Bind("TestAuthenticationBind", tb);
AuthenticationController.cs
private readonly AuthenticationBind authenticationBind;
public AuthenticationController(AuthenticationBind authenticationBind)
{
this.authenticationBind = authenticationBind;
}
另外,我可以使用物件實體傳遞給 services.AddSingleton 方法,而不是類本身,如下所示?
builder.Services.AddSingleton<tb>();
uj5u.com熱心網友回復:
您似乎正在嘗試將配置值系結到模型中。您可以通過呼叫來執行此操作IServiceCollection.Configure<T>()- 對于您的代碼,它看起來像這樣:
builder.Services.Configure<AuthenticationBind>(builder.Configuration.GetSection("TestAuthenticationBind"));
之后,您可以使用IOptions<T>控制器中的介面來訪問(系結)物件:
public AuthenticationController(
IOptions<AuthenticationBind> authOptions
)
{
// You can access authOptions.Value here
}
在啟動類中也是如此,您可以IOptions像這樣請求介面:
var authOptions = app.Services.GetRequiredService<IOptions<AuthenticationBind>>();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/469477.html
