gpt4 book ai didi

c# - 如何解析 ConfigureServices 中的 IOptions 实例?

转载 作者:IT王子 更新时间:2023-10-29 03:45:39 25 4
gpt4 key购买 nike

是否可以解析 IOptions<AppSettings> 的实例?来自 ConfigureServices启动时的方法? The documentation explicitly says :

Don't use IOptions<TOptions> or IOptionsMonitor<TOptions> in Startup.ConfigureServices. An inconsistent options state may exist due to the ordering of service registrations.

您可以使用 serviceCollection.BuildServiceProvider() 手动创建服务提供者但这会导致警告:

Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.

我怎样才能做到这一点?

public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(
configuration.GetConfigurationSection(nameof(AppSettings)));

// How can I resolve IOptions<AppSettings> here?
}

最佳答案

如果您需要使用服务提供者手动解析服务,您可以使用此 AddSingleton/AddScoped/AddTransient 重载:

// Works for AddScoped and AddTransient as well
services.AddSingleton<IBarService>(sp =>
{
var fooService = sp.GetRequiredService<IFooService>();
return new BarService(fooService);
}

如果您真的想要,您可以使用 IServiceCollection 上的 BuildServiceProvider() 方法构建一个中间服务提供者:

public void ConfigureService(IServiceCollection services)
{
// Configure the services
services.AddTransient<IFooService, FooServiceImpl>();
services.Configure<AppSettings>(configuration.GetSection(nameof(AppSettings)));

// Build an intermediate service provider
var sp = services.BuildServiceProvider();

// Resolve the services from the service provider
var fooService = sp.GetService<IFooService>();
var options = sp.GetService<IOptions<AppSettings>>();
}

为此,您需要 Microsoft.Extensions.DependencyInjection 包。

但是,请注意,这会导致多个服务提供者实例,进而可能导致多个单例实例。


如果只需要在ConfigureServices中绑定(bind)一些选项,也可以使用Bind方法:

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

此功能可通过 Microsoft.Extensions.Configuration.Binder 包获得。

关于c# - 如何解析 ConfigureServices 中的 IOptions 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31863981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com