NoviceCoder
NoviceCoder

Reputation: 519

Calling multiple httpclient that contain two different base address

I have read up on named clients and typed clients in order to achieve my ultimate goal. However, I still do not understand how I need to implement either or. I have a blazor server side project that in the startup.cs file I have it set up as

services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri("http://localhost:36626") });

services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri("https://localhost:5443") });

I know that if I do this, the baseaddress of the first one will completely be overwritten and no longer be the set base address due to the second baseaddress. How would I go about making this work so that way I have two separate httpclients that will have two separate baseaddress without having to lose one because of the most recent line of code?

Upvotes: 1

Views: 2651

Answers (1)

Frank
Frank

Reputation: 317

As said in the doc, the main differences are in how you are going to get an instance through Dependency Injection.

With Named Client you need to inject the factory and then get the client by a string.

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

With Typed Client you can inject the client needed as a type.

//GitHubService encapsulate an HTTP client
public TypedClientModel(GitHubService gitHubService)
    {
        _gitHubService = gitHubService;
    }

Both of them give the solution to your problem. The selection is more in how comfortable you are with the dependency injection method of each one. I personally prefer the Typed client.

Upvotes: 2

Related Questions