c# – Autofac – SingleInstance HttpClient

已经在各个地方读过HttpClient应该被重用而不是每次都有一个新实例.

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

我在一个项目上使用Autofac.

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

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

好像工作:)

解决方法:

如果您在整个应用程序生命周期中需要一个,那么这非常好,但是您可能希望根据API端点对其进行不同的配置.

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();
上一篇:c# – Autofac – 方法注入示例


下一篇:c# – Autofac – 动态解析带参数的组件