在.net 6中,当服务初始化出现在值的配置绑定之前时,我如何将参数传递给构造函数?



我似乎找不到解决我的确切问题的方法,因为我需要在调用构建器之前调用依赖注入,但这会导致控制器类中的新对象实例化并且值丢失。如果我把这行放在绑定之后,我可能会得到一个错误,说不能在服务构建后修改它。

在旧版本的。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": "*"
}

Program.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;
}

同样,我可以使用对象实例传递给服务。AddSingleton方法,而不是类本身,如下所示?

builder.Services.AddSingleton<tb>();

看起来您正在尝试将配置值绑定到模型中。您可以通过调用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>>();

最新更新