Autofac-SingleInstance HttpClient [英] Autofac - SingleInstance HttpClient

查看:178
本文介绍了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天全站免登陆