Lea*_*sed 4 c# nopcommerce asp.net-core-mvc
我试图了解如何HttpClient在 Nop Commerce 中为 Captcha 实施,以及为了可测试性,如何HttpClient在 Nop Commerce 项目中管理创建新实例。
我遇到了ValidateCaptchaAttribute,ValidateCaptchaFilter我看到 HttpClient 已经被包裹在CaptchaHttpClient类中,但我不明白从哪里CaptchaHttpClient接收依赖HttpClient以及从哪里CaptchaHttpClient调用类的构造函数。
在ServiceCollectionExtensions课堂内,我看到以下代码:
public static void AddNopHttpClients(this IServiceCollection services)
{
//default client
services.AddHttpClient(NopHttpDefaults.DefaultHttpClient).WithProxy();
//client to request current store
services.AddHttpClient<StoreHttpClient>();
//client to request nopCommerce official site
services.AddHttpClient<NopHttpClient>().WithProxy();
//client to request reCAPTCHA service
services.AddHttpClient<CaptchaHttpClient>().WithProxy();
}
Run Code Online (Sandbox Code Playgroud)
但我没有看到 HttpClient 对象是在哪里创建的:
var client = new HttpClient() // Where this is done?
Run Code Online (Sandbox Code Playgroud)
我可能错过了什么吗?
Nop 商务版 = 4.20
Sco*_*nen 14
从文档:
将 IHttpClientFactory 和相关服务添加到 IServiceCollection 并配置 TClient 类型和命名的 HttpClient 之间的绑定。客户端名称将设置为 TClient 的类型名称。
粗略翻译,services.AddHttpClient<CaptchaHttpClient>()意味着CaptchaHttpClient依赖于HttpClient. 这表示在注入HttpClient到 时CaptchaHttpClient,不要只是创建一个新的 - 使用 的实现IHttpClientFactory来提供一个并注入它。
这意味着您没有管理HttpClient. 这ServiceProvider是在幕后做的。
本文档解释了它为什么存在以及它是如何工作的。
Typed Client 实际上是一个瞬态对象,这意味着每次需要时都会创建一个新实例,并且每次构造它时都会收到一个新的 HttpClient 实例。但是,池中的 HttpMessageHandler 对象是多个 Http 请求重复使用的对象。
这意味着:
CaptchaHttpClient是暂时的,因此每次解决时,都会创建一个新实例。HttpClient都会创建并注入一个新的。HttpClient是新的,但HttpMessageHandler它所依赖的被重用。这使用了HttpMessageHandler我们不必管理的实例池。我们的类只是依赖HttpClient而不必担心HttpClient每次我们需要一个时创建/处置一个时发生的负面影响。
| 归档时间: |
|
| 查看次数: |
14131 次 |
| 最近记录: |