Home > Software engineering >  HttpClientFactory and typed-client?
HttpClientFactory and typed-client?

Time:08-22

I'm new in implementing HttpClientFactory. I've read a document about ways to implement. in my code there are services and its interfaces so I want to use typed-client. but I have a question?! in typed-client, we don't use HttpClientFactory directly so where is the benefit of the HttpClientFactory? this is my code to register service:

var clientConf = configuration.GetSection(nameof(ClientConfigs));
builder.Services.AddHttpClient<IClientService, ClientService>(c =>
{
    c.BaseAddress = new Uri(clientConf.GetSection("EndPoint").Value);
 }).AddHttpMessageHandler<ServiceCallRequestHeader>();

this is ctor of my service:

  public ClientService(HttpClient client, ILogger<ClientService> logger)
    {
        _client = client;
        _logger = logger;
    }

CodePudding user response:

In Typed-Client, Dotnet uses HttpClientFactory to create the instance of HttpClient, using that instance they will create your client/class instance. So in the end, even if you are not using HttpClientFactory explicitly, you are using it.

Below is the internal code that does this enter image description here Source: HttpClientBuilderExtensions.cs

  • Related