我似乎找不到解决我的确切问题的方法,因为我需要在调用构建器之前调用依赖项注入(inject),但这会导致 Controller 类中出现新的对象实例化,并且值会丢失。 如果我在绑定(bind)后立即放置此行,则会收到一条错误消息,指出构建后无法修改服务。
在旧版本的.net中,由于Startup.cs已经存在,因此由于方法ConfigureService和Configure的分离,这似乎不是问题。
AuthenticationBind.cs
public class AuthenticationBind
{
public int AuthenticationId { get; set; }
public string AuthenticationName { get; set; }
}
appsettings.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>();
最佳答案
您似乎正在尝试 bind configuration values into models 。您可以通过调用IServiceCollection.Configure<T>()
来做到这一点- 对于您的代码,它看起来像这样:
builder.Services.Configure<AuthenticationBind>(builder.Configuration.GetSection("TestAuthenticationBind"));
之后,您可以使用IOptions<T>
Controller 中用于访问(绑定(bind))对象的接口(interface):
public AuthenticationController(
IOptions<AuthenticationBind> authOptions
)
{
// You can access authOptions.Value here
}
启动类也是如此,您可以请求 IOptions
界面如下:
var authOptions = app.Services.GetRequiredService<IOptions<AuthenticationBind>>();
关于c# - 在.net 6中,当服务初始化发生在值的配置绑定(bind)之前时,如何将参数传递给构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72074839/