【发布时间】:2020-10-28 18:19:37
【问题描述】:
帮派怎么了?
我正在寻找一种使用 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"
}
}
提前致谢!
【问题讨论】:
-
显示你的
AppSettings类和json -
已添加。问题是应用程序的其余部分可以很好地获取设置,因此配置解析肯定是正确的。
标签: asp.net-core dependency-injection