liveBook · Manning

AddHttpClient

As explained in ASP.NET Core in Action, 3e

AddHttpClient is a .NET dependency-injection extension method that registers an HttpClient and optionally associates its configuration with a typed or named client.

AddHttpClient registers HttpClient with dependency injection and can associate configuration with a typed client. A typed client keeps remote-service HTTP logic behind a focused C# API. section 33.2.3

A typed-client registration provides several pieces at once:

  • Registers HttpClient as a transient service backed by a pooled instance managed by IHttpClientFactory. section 33.2.3
  • Registers the typed client as transient and configures the injected HttpClient through the AddHttpClient<T> callback. section 33.2.3
  • Supports a typed client interface, such as IExchangeRatesClient, to make consuming code easier to test. section 33.2.3
  • Can leave configuration in the client constructor instead, although central registration keeps endpoint settings visible in startup code. section 33.2.3

Register and consume a typed client

Register ExchangeRatesClient with AddHttpClient, set its BaseAddress and User-Agent, then inject it into an endpoint. The endpoint calls GetLatestRates without constructing requests or selecting a client by string name.

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains typed-client registration, transient services, pooled handlers, and configuration alternatives without detailing handler implementation.
Examples
Uses ExchangeRatesClient with BaseAddress, User-Agent configuration, constructor injection, and an endpoint consuming GetLatestRates.
What it assumes
Assumes basic C# classes, constructors, dependency injection, and asynchronous HTTP calls while demonstrating typed-client structure from the example.
What you can do after
Builds a typed HTTP client, registers it with AddHttpClient, configures its endpoint, and injects it into application code.
How it connects
Connects dependency injection, IHttpClientFactory, typed clients, named clients, HttpClient, and Polly error-handling policies.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.