You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过助手类结合Options Pattern获取appsettings配置?

问题解决方案

你的核心问题在于没有充分利用依赖注入容器来管理对象的依赖关系,而是手动实例化类导致无法正确传递IOptions<WsdotConfigOptions>依赖。下面是具体的修复步骤和代码示例:

1. 修改DisplayInfo类,通过构造函数注入RouteHelper

不要手动new RouteHelper(),而是让依赖注入容器自动提供该实例:

private BorderInfo borderInfo { get; set; }
private MountainPassInfo mpInfo { get; set; }
private UrlSetup url { get; set; }
private Messaging message { get; set; }
private RouteHelper _routeHelper{ get; set; }

// 通过构造函数注入RouteHelper,无需手动实例化
public DisplayInfo(RouteHelper routeHelper)
{
    borderInfo = new BorderInfo();
    mpInfo = new MountainPassInfo();
    url = new UrlSetup();
    message = new Messaging();
    _routeHelper = routeHelper;
}

// 如果DisplayInfo确实需要直接使用IConfiguration,可同时注入
// public DisplayInfo(RouteHelper routeHelper, IConfiguration config)
// {
//     // 初始化其他字段
//     _routeHelper = routeHelper;
// }

2. 更新Program.cs,注册所有服务并通过容器解析实例

将RouteHelper和DisplayInfo注册到服务容器中,让容器自动处理依赖链:

IConfiguration configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: false)
        .Build();

var services = new ServiceCollection();
// 注册配置选项
services.Configure<WsdotConfigOptions>(configuration.GetSection("WSDOT"));
// 注册RouteHelper(根据业务需求选择生命周期:Transient/Scoped/Singleton)
services.AddTransient<RouteHelper>();
// 注册DisplayInfo
services.AddTransient<DisplayInfo>();

// 构建服务提供者并解析DisplayInfo实例
using var serviceProvider = services.BuildServiceProvider();
DisplayInfo display = serviceProvider.GetRequiredService<DisplayInfo>();

while (true)
{
    display.DisplaySelection();
}

关键说明

  • 依赖注入容器会自动处理RouteHelper所需的IOptions<WsdotConfigOptions>实例,无需手动传递
  • 如果BorderInfo、MountainPassInfo等其他类也有依赖,建议同样通过构造函数注入并注册到服务容器,保持代码一致性
  • 服务生命周期选择:
    • AddTransient:每次获取服务时创建新实例
    • AddScoped:在同一作用域内复用实例
    • AddSingleton:全局只创建一个实例

内容的提问来源于stack exchange,提问作者DonDavid12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 13:52:42