Autofac - SingleInstance HttpClient [英] Autofac - SingleInstance HttpClient

查看:45
本文介绍了Autofac - SingleInstance HttpClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在很多地方都读到过 HttpClient 应该被重用,而不是每次都创建一个新实例.

Have read in various places that HttpClient should be reused rather than a new instance every time.

https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

我在一个项目中使用 Autofac.

I am using Autofac on a project.

这是使 HttpClient 的单个实例可用于注入服务的好方法吗?

Would this be a good way of making a single instance of HttpClient available to to inject into services?

builder.Register(c => new HttpClient()).As<HttpClient>().SingleInstance();

似乎有效:)

推荐答案

如果您希望在整个应用程序生命周期中使用一个,这完全没问题,但您可能希望针对每个 API 端点对其进行不同的配置.

That's perfectly fine if you want one per whole application lifecycle however you might want to configure it different per API endpoint.

builder.Register(ctx => new HttpClient() {BaseAddress = new Uri("https://api.ipify.org")})
    .Named<HttpClient>("ipify")
    .SingleInstance();

builder.Register(ctx => new HttpClient() { BaseAddress = new Uri("https://api.postcodes.io") })
    .Named<HttpClient>("postcodes.io")
    .SingleInstance();

然后说我们有一个 PostcodeQueryHandler

public class PostcodeQueryHandler
{
    public PostcodeQueryHandler(HttpClient httpClient) { }
}

我们会像

builder.Register(ctx => new PostcodeQueryHandler(ctx.ResolveNamed<HttpClient>("postcodes.io")))
        .InstancePerDependency();

这篇关于Autofac - SingleInstance HttpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆