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/
I am using Autofac on a project.
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();
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.
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With