2016-11-07 78 views
6

我需要在ASP.NET Core 1.0 Web應用程序的ConfigureServices方法中設置一些依賴關係(服務)。實際上在ASP.NET Core的ConfigureServices階段閱讀AppSettings

問題是,基於新的JSON配置,我需要設置一個服務或其他。

我似乎無法實際讀的應用程序生命週期的ConfigureServices階段設置:

public void ConfigureServices(IServiceCollection services) 
{ 
    var section = Configuration.GetSection("MySettings"); // this does not actually hold the settings 
    services.Configure<MySettingsClass>(section); // this is a setup instruction, I can't actually get a MySettingsClass instance with the settings 
    // ... 
    // set up services 
    services.AddSingleton(typeof(ISomething), typeof(ConcreteSomething)); 
} 

我需要真正的閱讀部分,並決定什麼爲ISomething註冊(可能是不同類型的比ConcreteSomething)。

+2

見http://stackoverflow.com/q/40397648/5426333 –

+0

@ademcaglin:謝謝!就是這樣。我投了贊成關閉自己的問題:) –

+0

鏈接的答案是從配置文件中獲取值,而不是appsettings.json文件。 – im1dermike

回答

1

從ASP.NET Core 2.0開始,在構建WebHost實例時,我們在Program類中做了配置設置。這樣的設置舉例:

return new WebHostBuilder() 
    .UseKestrel() 
    .UseContentRoot(Directory.GetCurrentDirectory()) 
    .ConfigureAppConfiguration((builderContext, config) => 
    { 
     IHostingEnvironment env = builderContext.HostingEnvironment; 

     config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) 
      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); 
    }) 

其中,這允許使用配置直接Startup類,通過構造函數注入(謝謝你,內置的DI容器)獲得的IConfiguration一個實例:

public class Startup 
{ 
    public Startup(IConfiguration configuration) 
    { 
     Configuration = configuration; 
    } 

    public IConfiguration Configuration { get; } 

    ... 
} 
+0

是的!爲我工作。最後,我可以從json條目中獲得我的東西來準備我的服務:\ – AmiNadimi

相關問題