.net 核心控制台应用程序强类型配置

.net core console app strongly typed configuration

有一个关于如何在 .net 核心控制台应用程序上创建强类型配置的 Whosebug 答案 ,但我的问题是如何将此强类型配置传递给其他服务;

像这样

static void Main(string[] args)
{
    //...
    .AddSingleton<IMyService, MyService>()
}

public class MyService
{
    private readonly IConfiguration _configuration;
    public MyService (IConfiguration configuration)
    {
        _configuration = configuration;
    }
}

这是 MS 文档中的示例 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1#accessing-options-during-startup

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddOptions<MyConfigOptions>()
            .Bind(Configuration.GetSection(MyConfigOptions.MyConfig))
            .ValidateDataAnnotations();

        services.AddControllersWithViews();
    }

消费者:

public HomeController(IOptions<MyConfigOptions> config,
                          ILogger<HomeController> logger)