如何解决ASP.NET核心实例中ConfigureServices [英] How to Resolve Instance Inside ConfigureServices in ASP.NET Core
本文介绍了如何解决ASP.NET核心实例中ConfigureServices的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能解决 IOptions<的实例;的AppSettings>
在启动的 ConfigureServices
的方法?通常情况下,你可以使用的IServiceProvider
来初始化实例,但你没有它在这个阶段,当你注册服务。
公共无效ConfigureServices(IServiceCollection服务)
{
services.Configure<&AppSettings的GT;(
configuration.GetConfigurationSection(nameof(的AppSettings)));
//如何解决IOptions<&AppSettings的GT;这里?
}
解决方案
您可以建立一个服务提供商用 IServiceCollection
的 BuildServiceProvider()
方法:
公共无效ConfigureService(IServiceCollection服务)
{
services.AddTransient< ISomeService,SomeService>();
变种SP = services.BuildServiceProvider();
VAR的服务= sp.GetService< ISomeService>();
}
您需要的 Microsoft.Framework.DependencyInjection
这一点。
Is it possible to resolve an instance of IOptions<AppSettings>
from the ConfigureServices
method in Startup? Normally you can use IServiceProvider
to initialize instances but you don't have it at this stage when you are registering services.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(
configuration.GetConfigurationSection(nameof(AppSettings)));
// How can I resolve IOptions<AppSettings> here?
}
解决方案
You can build a service provider using the BuildServiceProvider()
method on the IServiceCollection
:
public void ConfigureService(IServiceCollection services)
{
services.AddTransient<ISomeService, SomeService>();
var sp = services.BuildServiceProvider();
var service = sp.GetService<ISomeService>();
}
You need the Microsoft.Framework.DependencyInjection
for this.
这篇关于如何解决ASP.NET核心实例中ConfigureServices的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文