1

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

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

4

1 回答 1

0

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

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

public readonly IConfiguration _configuration;

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

于 2017-08-21T10:05:23.637 回答