c# - 在.net 6中,当服务初始化发生在值的配置绑定(bind)之前时,如何将参数传递给构造函数?

标签 c# asp.net-core .net-core

我似乎找不到解决我的确切问题的方法,因为我需要在调用构建器之前调用依赖项注入(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/

相关文章:

c# - 如何在 ASP.NET Core 中默认防止 CSRF

asp.net - 在.NET core中更改身份登录的成功url改为/Home/Index

linux - dotnet 命令找不到 .NET Core 2.1 的新安装

c# - 如何向我的 User 类添加附加功能

c# - 使用 Thread.Sleep 时如何更新 UI

c# - 在内存中操作文本文件的最佳方法 : read as byte[] first? 读取为 File.ReadAllText() 然后另存为二进制文件?

c# - 如何将自定义信息存储到 Outlook AppointmentItem

c# - 从服务器端 Blazor 应用程序调用 API 时,用户声明始终为空

asp.net-mvc - 如何使用 .NET Core 中间件将 HTML 插入响应主体

asp.net-core - 填充 AspNetUserLogins 和 AspNetUserTokens