[英]Autofac - SingleInstance HttpClient
Have read in various places that HttpClient should be reused rather than a new instance every time. 已经在各个地方读过HttpClient应该被重用而不是每次都有一个新实例。
https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
I am using Autofac on a project. 我在一个项目上使用Autofac。
Would this be a good way of making a single instance of HttpClient available to to inject into services? 这是一个让HttpClient的单个实例可用于注入服务的好方法吗?
builder.Register(c => new HttpClient()).As<HttpClient>().SingleInstance();
Seems to work :) 好像工作:)
That's perfectly fine if you want one per whole application lifecycle however you might want to configure it different per API endpoint. 如果您在整个应用程序生命周期中需要一个,那么这非常好,但是您可能希望根据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();
Then say we have a PostcodeQueryHandler
然后说我们有一个PostcodeQueryHandler
public class PostcodeQueryHandler
{
public PostcodeQueryHandler(HttpClient httpClient) { }
}
We'd set up the bindings like 我们设置了绑定
builder.Register(ctx => new PostcodeQueryHandler(ctx.ResolveNamed<HttpClient>("postcodes.io")))
.InstancePerDependency();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.