如何在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
- 将文件从ASP.NET Core web api发布到另一个ASP.NET Core web api
- 为所有控制器全局validationModelState.IsValid
- Resolver或ServiceProvider使用ICompositeViewEngine所需的依赖项
- ASP.NET核心JWT承载令牌自定义validation
- Asp.Net核心长期运行/后台任务
- 在ASP.NET中使用dependency injection和工厂模式传递服务
- 使用Azure中的ASP.NET Core在Redis中保存用户会话
- ASP.NET VNext调试MVC源代码
- ASP NET 5使用单独程序集中的View组件进行本地化