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

时间:2017-08-21 09:37:30

标签: c# asp.net asp.net-core asp.net-core-2.0 asp.net-core-configuration

在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")),    
  );
}

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

1 个答案:

答案 0 :(得分:0)

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

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

public readonly IConfiguration _configuration;

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