Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share HttpClient between services

I am working on a Blazor project, and to make the question I have easier to understand, we can say that I am using two different services that handles the Authentication part. Those are registered in the configureservices startup method together with a named httpclient.

services.AddHttpClient("XBOWServicesApi", c =>
{
c.BaseAddress = new Uri(XBOWServicesApi);
});

services.AddSingleton<IService1, Service1>();
services.AddSingleton<IService2, Service2>();

Service 1: Wraps all functionality available in a REST Api. It uses an http client which is set in the constructor via an instanciated httpclientfactory. This needs to be set with a baseurl and an Auth-header to work.

public Service1(IHttpClientFactory clientFactory)
{
this.httpClient = clientFactory.CreateClient("XBOWServicesApi");
}

Service 2: Handles the login/logout functionality using a custom AuthenticationStateProvider. It has its own httpclient, so that I can set the Auth Header for the http client. The constructor works in the same way as for Service 1.

public Service2(IHttpClientFactory clientFactory)
{
this.httpClient = clientFactory.CreateClient("XBOWServicesApi");
}

The reason for this build up is of course that I like to share the same http client, so when it is set in the login/logout methods, service 1 will have the correct auth header when communicating with the api.

However, the client factory provides a new instance everytime, so this will never work.

Any ideas how to handle this?

/Henrik

like image 372
Henrik Bengtsson Avatar asked Jul 26 '26 16:07

Henrik Bengtsson


1 Answers

You can use named client:

services.AddHttpClient("github", c =>
{
    c.BaseAddress = new Uri("https://api.github.com/");
    // Github API versioning
    c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
    // Github requires a user-agent
    c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
});

Afterwards, just call CreateClient method with corresponding name parameter.

var client = _clientFactory.CreateClient("github");

Each time CreateClient is called:

  • A new instance of HttpClient is created.
  • The configuration action is called.

You can find more details in Microsoft documentation here.

like image 182
Nenad Avatar answered Jul 29 '26 05:07

Nenad