Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac - SingleInstance HttpClient

Tags:

c#

.net

autofac

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

like image 386
wingyip Avatar asked May 17 '18 14:05

wingyip


1 Answers

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();
like image 67
Kevin Smith Avatar answered Sep 20 '22 18:09

Kevin Smith