简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM