25

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 inject into services?

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

Seems to work :)

wingyip
  • 3,465
  • 2
  • 34
  • 52

1 Answers1

35

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();
Kevin Smith
  • 13,746
  • 4
  • 52
  • 77
  • 3
    I just want to add that `InstancePerDependency()` is the default behavior and you may skip it if you want. [InstancePerDependency Method](https://autofac.org/apidoc/html/B7A3F094.htm) – Ivo Gluhchev Dec 05 '18 at 08:49
  • @Kevin Smith thanks for the alternative! It's nice to have both of these solutions here in one place. – ganjeii Aug 30 '19 at 23:43