将配置选项从 netcoreapp1.1 移植到 netcoreapp2.0

Porting configuration options from netcoreapp1.1 to netcoreapp2.0

在 netcoreapp1.1 中,我的配置是在 Startup 中定义的,其中包含:

public Startup(IHostingEnvironment env)
{
  _configuration = 
    new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json")
    .Build();
}

private readonly IConfigurationRoot _configuration;

public IServiceProvider ConfigureServices(IServiceCollection services)
{
  services.AddOptions();
  services.Configure<Stuff1>(_configuration.GetSection("stuff1"));
  services.Configure<Stuff2>(_configuration.GetSection("stuff2"));

  services.AddDbContext<Context>(options =>
    options.UseSqlite(_configuration.GetConnectionString("DefaultConnection")),    
  );
}

但在netcoreapp2.0 中配置是在Program 中单独定义的。所以 Startup 现在只有这个:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
  var configuration = //???   how do I get this?

  services.AddOptions();
  services.Configure<Stuff1>(configuration.GetSection("stuff1"));
  services.Configure<Stuff2>(configuration.GetSection("stuff2"));

  services.AddDbContext<Context>(options =>
    options.UseSqlite(configuration.GetConnectionString("DefaultConnection")),    
  );
}

那么如何在 ConfigureServices() 中获取 IConfigurationRoot,以便我可以设置我的强类型 Stuff1Stuff2 选项,以及连接等其他内容字符串?

原来它是自动注册到容器中的,并且可以像这样使用:

public Startup(IConfiguration configuration)
{
    _configuration = configuration;
}

public readonly IConfiguration _configuration;

这对我有用,但我认为也可以使用 IConfigurationRoot