簡體   English   中英

如何在啟動 class 中使用強類型配置

[英]How can I use a strongly-typed config within the Startup class

我有一個強類型配置工作,但我正在努力在“類啟動”中使用強類型 class

這是我在啟動時的代碼:

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IHostEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Allow sites to hit the API
        services.AddCors();

        // Add Mvc Routes
        services.AddMvc(option => option.EnableEndpointRouting = false);

        // Add custom configuration
        services.Configure<Config>(Configuration);

我想在該文件的另一個 function 中使用強類型 class ,但我不確定我該怎么做......

這是它在其他類中的工作方式:

    readonly Config Config = null;

    public EmailController(IOptions<Config> config) 
    {
        Config = config.Value;
    }

但是,如果我嘗試將相同的代碼添加到我的“類啟動”中,那么我會得到這個異常

System.ArgumentNullException: '值不能是 null。 (參數'配置')'

在線上

services.Configure<Config>(Configuration);

我想您是在問如何在啟動 class 中使用您的配置,然后才能將其注入構造函數?

您可以在 IConfiguration 上使用 Get 或 Bind 方法


// Add custom configuration
services.Configure<Config>(Configuration);

//Get the config object for use here
var config = Configuration.Get<Config>();


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM