给定以下.NET Core 2.2类定义:
public class MyService : ISomeService
{
public MyService(string apiKey, HttpClient httpClient) { ... }
}
如何将DI设置为使用HttpClientFactory
并在将ISomeService构造函数注入其他类时使用此具体实例?例如。
services.AddHttpClient<ISomeService, MyService>();
services.AddSingleton<ISomeService, MyService>(
sp => new MyService("some api key from config", sp.GetService<??????????>() );
将apiKey
配置值提升为参数对象:
public sealed class MyServiceConfiguration
{
public readonly string ApiKey;
public MyServiceConfiguration(string apiKey)
{
if (string.IsNullOrEmpty(apiKey)) throw new ArgumentException(...);
this.ApiKey = apiKey;
}
}
并将您的MyService
构造函数更改为:
public MyService(MyServiceConfiguration config, HttpClient httpClient)
新的MyServiceConfiguration
可以很容易地注册如下:
services.AddSingleton(new MyServiceConfiguration("some api key from config"));
请注意使用HttpClient
注入Singleton
消费者。如here,here和here所述,当HttpClient
实例在应用程序的持续时间内重复使用时会出现许多问题,这些问题将与您当前的配置一起使用。当您将MyService
注册为Singleton
时,HttpClient
将成为Captive Dependency。
相反,注册你的MyService
为Scoped
。 Ideally,ASP.NET Core应该能够为你检测这个Captive Dependency,但是在它当前的实现(v2.2)中它没有这样做,这意味着你最好通过制作你的直接消费者Scoped
来保护自己(和清楚地记录为什么会这样,以防止下一个开发人员再次搞砸了事情。