启动时使用IOptions的aspnet核心依赖项注入



帮派发生了什么?

我正在寻找一种使用IOptions包将配置注入类的正确而干净的方法。目前,我正在一个地方注册所有的配置对象,一切都很好。问题是我需要在启动方法中注册的一些类。

最初的方法实现如下:(扩展方法(

public static void RegisterHttpClients(this IServiceCollection services, AppSettings appSettings)
{
services.AddHttpClient<IPdfService, PdfService>(
httpClient => httpClient.DefaultRequestHeaders.Add("PdfApiKey", appSettings.PdfApiKey));
}

这个AppSettings对象我也使用IOptions注入到其他类中,所以我想以某种方式重用那里的对象,而不必像这样再次从json中获得相同的对象:

var appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
services.RegisterHttpClients(appSettings);

换言之,我已经在services.Configure<AppSettings>(configuration.GetSection("AppSettings"));上注册了这个东西,所以如果可能的话,我想继续做下去。

关于如何配置,有什么想法/建议吗?

编辑:(添加了JSON和AppSettings文件(

public class AppSettings 
{
public string PdfApiKey {get; set;}
public string AnotherProperty {get; set;}
}
{
"AppSettings": {
"PdfApiKey": "SomeKey",
"AnotherProperty": "HollyTheCow"
}
}

提前感谢!

您可以通过向Configure注册选项(您已经完成了(,然后使用AddHttpClient()的第二个重载从DI容器(服务定位器模式(中获取已注册的选项来实现这一点。注意,我使用了IServiceProvider.GetRequiredService,但如果它是可选设置,则可以使用IServiceProvider.GetService()?.Value

services.Configure<AppSettings>(_configuration.GetSection("AppSettings"));
services.AddHttpClient<YourService>((serviceProvider, config) => {
var settings = serviceProvider.GetRequiredService<IOptions<AppSettings>>().Value;
config.BaseAddress = new Uri(settings.BaseUri);
});

您的代码没有任何错误,将成功运行

您的项目中可能有许多appSetting.json文件。

检查项目中的ASPNETCORE_ENVIRONMENT变量。

右键单击您的项目>属性>调试>环境变量

如果在开发IConfiguration上设置了ASPNETCORE_ENVIRONMENT,则从appSettings.development.json,您应该在appSettings.development.json中添加AppSettigsjson

如果ASPNETCORE_ENVIRONMENT设置为生产IConfigurationappSettings.production.json,您应该在appSettings.production.json中添加AppSettigsjson

如果您希望IConfigurationappSetting.json读取数据,请同时删除appSettings.development.jsonappSettings.product.json文件。

在这种情况下,默认情况下IConfigurationappSetting.json读取并绑定数据

其他选项

您可以将IConfiguration配置为从appSettings.json像这个

public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
this.configuration = builder.Build();
}

最新更新