Skip to content

Specifics of using SystemHttpTransport

Stanislav Molchanovskiy edited this page Nov 15, 2021 · 2 revisions

An HttpClient is created for each instance of a client. Keep this in mind, because the HttpClient has problems. Create an instance for every request and you will run into socket exhaustion. Make it a singleton and it will not respect DNS changes. The best way would be to use IHttpClientFactory. You can create it yourself and pass it to the builder:

IHttpClientFactory httpClientFactory = ...;

IMyClient myClient = NClientGallery.Clients.GetRest()
    .For<IMyClient>(host)
    .UsingSystemHttpTransport(httpClientFactory)
    .Build();

For more fine-tuning, you can use a named HttpClient:

IMyClient myClient = NClientGallery.Clients.GetRest()
    .For<IMyClient>(host)
    .UsingSystemHttpTransport(httpClientFactory, httpClientName: "myHttpClient")
    .Build();

But perhaps the best option is to use DI extensions (see Dependency injection section):

var serviceProvider = new ServiceCollection()
    .AddHttpClient()
    .AddNClient<IMyClient>(host: "http://localhost:8080")
    .BuildServiceProvider();

IMyClient myClient = serviceProvider.GetRequiredService<IMyClient>();

Clone this wiki locally