我正在尝试将 IOptions 注入到需要 HttpClient 和 IOptions 的类中。
public class MyHttpService : IMyHttpService
{
private readonly HttpClient _httpClient;
private readonly IOptions<MyOption> _myOption;
MyHttpService(HttpClient httpClient, IOptions<MyOption> myOption)
{
_httpClient = httpClient;
_myOption = myOption;
}
//Further methods be here...
}
public class MyOption
{
public string MyStringSetting {get;set;}
//More settings be here...
}
appsettings.json 内部
{
"MyOptions":{
"MyStringSetting": "SomeSetting"
}
}
程序内部.cs
IWebHostBuilder builder =
WebHost.CreateDefaultBuilder(args)
.Configure()
.ConfigureLogging()
.UseNLog()
.ConfigureServices((context, services) =>
{
services.AddOptions();
IConfiguration configuration = context.Configuration;
services.Configure<MyOption>(configuration.GetSection("MyOptions"));
services.AddHttpClient<IMyHttpService,MyHttpService>((provider,client) =>
{
client.BaseAddress = new Uri(\*api url*\);
});
})
IWebHost webHost = builder.build();
webHost.Run();
在调查 MyHttpService 时,它没有注入 IOptions。 我错过了什么?
我期望
ConfigureServices()
能够解决 IOptions 依赖关系并注入已实现的 MyOptions。
实际上注入了 IOptions 依赖项。还有另一个类正在使用另一个需要配置的 IOptions 实现。