如何在ASP.NET Core中解析ConfigureServices中的实例

是否可以从Startup中的ConfigureServices方法解析IOptions的实例? 通常,您可以使用IServiceProvider初始化实例,但在注册服务时此阶段没有它。

 public void ConfigureServices(IServiceCollection services) { services.Configure( configuration.GetConfigurationSection(nameof(AppSettings))); // How can I resolve IOptions here? } 

您可以使用IServiceCollection上的BuildServiceProvider()方法构建服务提供者:

 public void ConfigureService(IServiceCollection services) { // Configure the services services.AddTransient(); services.Configure(configuration.GetSection(nameof(AppSettings))); // Build an intermediate service provider var sp = services.BuildServiceProvider(); // Resolve the services from the service provider var fooService = sp.GetService(); var options = sp.GetService>(); } 

您需要Microsoft.Extensions.DependencyInjection包。


如果您只需要在ConfigureServices绑定一些选项,您还可以使用Bind方法:

 var appSettings = new AppSettings(); configuration.GetSection(nameof(AppSettings)).Bind(appSettings); 

可以通过Microsoft.Extensions.Configuration.Binder包获得此function。

你在寻找类似的东西吗? 您可以在代码中查看我的评论:

 // this call would new-up `AppSettings` type services.Configure(appSettings => { // bind the newed-up type with the data from the configuration section ConfigurationBinder.Bind(appSettings, Configuration.GetConfigurationSection(nameof(AppSettings))); // modify these settings if you want to }); // your updated app settings should be available through DI now