简体   繁体   English

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

[英].net core console app strongly typed configuration

There is a stackoverflow answer here on how to create strongly typed configuration on a .net core console app but my question is how do you pass this strongly typed configuration to other services;有一个计算器的答案在这里就如何在.NET核心控制台应用程序创建强类型的配置,但我的问题是你如何通过这个强类型的配置等服务;

something like this像这样的东西

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

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

Here's an example from MS documentation https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1#accessing-options-during-startup这是 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();
    }

And consumer:和消费者:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM