wingyip
wingyip

Reputation: 3536

Autofac - SingleInstance 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/

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 :)

Upvotes: 25

Views: 10706

Answers (1)

Kevin Smith
Kevin Smith

Reputation: 14456

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();

Upvotes: 36

Related Questions