Implement your Typed Client classes that use the injected and configured HttpClient As a previous step, you need to have your Typed Client classes defined, such as the classes in the
sample code, like ‘BasketService’, ‘CatalogService’, ‘OrderingService’, etc. –
A Typed Client is a class
that accepts an
HttpClient
object (injected through its constructor) and uses it to call some remote
HTTP service. For example:
public class CatalogService : ICatalogService
{
private readonly HttpClient _httpClient;
private readonly string
_remoteServiceBaseUrl;
public CatalogService
(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task GetCatalogItems
(
int
page,
int
take,
int
? brand,
int
? type)
{
var
uri = API.
Catalog
.
GetAllCatalogItems
(_remoteServiceBaseUrl,
page, take, brand, type);
var
responseString = await _httpClient.
GetStringAsync
(uri);
var
catalog = JsonConvert.
DeserializeObject
(responseString);
return catalog;
}
}
The Typed Client (
CatalogService
in the example) is activated by DI (Dependency Injection), which
means it can accept any registered service in its constructor, in addition to
HttpClient
.
A Typed Client is effectively a transient object, that means a new instance is created each time one is
needed. It receives a new
HttpClient
instance each time it’s constructed. However, the
HttpMessageHandler
objects in the pool are the objects that are reused by multiple
HttpClient
instances.