无法解决死的简单配置依赖

Unable to resolve dead simple configuration dependency

我正在尝试在基于 blazor 的小型 Web 应用程序中设置依赖项注入。

我当前的代码是:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();

AddDeliveryStats(builder.Services, builder.Configuration);

// ...blazor template things...

void AddDeliveryStats(IServiceCollection services, ConfigurationManager config)
{
    services.Configure<BigQuerySettings>(config.GetSection("BigQuery"));
    services.AddTransient<IBigQueryClient, BigQueryClient>();
    // ...other stuff not pertinent to the error...
}

其中 BigQuerySettings 给出为

public class BigQuerySettings
{
    public string ProjectId { get; set; }
    public string DataSetId { get; set; }
    public string AuthFilePath { get; set; }
}

BigQueryClient 具有以下构造函数:

public BigQueryClient(
    BigQuerySettings bigQuerySettings,
    ILogger<BigQueryClient> logger) { /* ... */ }

我的 appsettings.json 包含以下内容:

{
  // ...
  "BigQuery": {
    "ProjectId": "<project-identifier>",
    "DataSetId": "",
    "AuthFilePath": "BigQueryAuthProd.json"
  }
}

如果这看起来很像教程示例,那是因为它基本上就是这样。它不起作用,原因不明。我收到以下错误:

Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: IBigQueryClient Lifetime: Transient ImplementationType: BigQueryClient': Unable to resolve service for type 'BigQuerySettings' while attempting to activate 'BigQueryClient'.)

我已经从在线教程示例中复制了这段代码,并根据自己的情况对其进行了适当的调整 类,并且我已经阅读了我能够找到的所有文档(其中大部分我都找不到理解)并用谷歌搜索错误消息中至少十种不同的关键字排列。没有什么能真正指出我做错了什么。

默认情况下,调用 services.Configure 将只允许将 IOption<BigQuerySettings> 注入您的消费者。

但是,如果您希望将 BigQuerySettings 直接注入您的消费者(我认为 you should),您应该执行以下操作:

BigQuerySettings settings =
    Configuration.GetSection("BigQuery").Get<BigQuerySettings>();

// TODO: Verify settings here (if required)

// Register BigQuerySettings as singleton in the container.
services.AddSingleton<BigQuerySettings>(settings);

这允许 BigQuerySettings 注入 BigQueryClient