c# - 未映射强类型配置设置

标签 c# asp.net-core

我正在尝试在我的 ASP.NET Core 2.1 应用程序中设置强类型配置设置。

在我的 startup.cs 文件中,我有以下代码:

services.Configure<AzureStorageConfig>(Configuration.GetSection("AzureStorageConfig"));

我的设置类 AzureStorageConfig 如下所示:

public class AzureStorageConfig
{
    public string StorageConnectionString { get; internal set; }
}

我的 appSetting.json:

{
 "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
        "Default": "Debug",
        "System": "Information",
        "Microsoft": "Information"
    }
 },
 "AzureStorageConfig": {
    "StorageConnectionString": "UseDevelopmentStorage=true"
 }
}

当我运行代码时,我的 AzureStorageConfig.StorageConnectionString 始终为空。

如果我在 startup.cs 文件中设置断点,我可以看到设置在那里:

enter image description here

但是当注入(inject) AzureStorageConfig 时,它是空的。

public class RestaurantService : IRestaurantService
{
    private AzureStorageConfig m_Config;

    public RestaurantService(IOptions<AzureStorageConfig> config)
    {
        m_Config = config.Value;
    }
}

enter image description here

我想我拥有此处描述的所有内容:https://weblog.west-wind.com/posts/2016/May/23/Strongly-Typed-Configuration-Settings-in-ASPNET-Core

最佳答案

您的 StorageConnectionString 属性有一个 internal setter,但这需要是 public 以便 Binder 在尝试时使用它从您的 Configuration 实例绑定(bind):

public class AzureStorageConfig
{
    public string StorageConnectionString { get; set; }
}

关于c# - 未映射强类型配置设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52766326/

相关文章:

c# - 将 char 隐式转换为整数有什么好处?

api - 具有 API key 和 JWT token 的 Net Core API

c# - 如何在局部 View 中获取模型属性名称

asp.net-core - 如何注入(inject)对特定 IHostedService 实现的引用?

C# 容器 - 矢量,。列表、队列、堆栈等

c# - 处理日期和时间跨度的好方法?

c# - LINQ to JSON - 查询对象或数组

c# - 在服务中注入(inject)模拟的 dbContext - 集成测试

asp.net-core - Blazor 内联编辑表并获取事件的所有组件值

c# - C# 中的嵌套泛型问题