create httpclient with httpclient factory typed in csharp

To create an HttpClient with HttpClientFactory typed in C#, you need to first configure the HttpClientFactory in the Startup class of your web application as shown below:

main.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient<IMyTypedHttpClient, MyTypedHttpClient>();
}
132 chars
5 lines

In this code snippet, we are configuring the HttpClientFactory to create a typed HttpClient of type IMyTypedHttpClient. Whenever an instance of IMyTypedHttpClient is requested, the factory will create an instance of MyTypedHttpClient.

Next, you need to define your typed HttpClient as shown below:

main.cs
public interface IMyTypedHttpClient
{
    Task<string> GetStringAsync(string url);
}

public class MyTypedHttpClient : IMyTypedHttpClient
{
    private readonly HttpClient _httpClient;

    public MyTypedHttpClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<string> GetStringAsync(string url)
    {
        var response = await _httpClient.GetAsync(url);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }
}
515 chars
22 lines

In this example, we are defining a typed HttpClient called MyTypedHttpClient which implements IMyTypedHttpClient. The constructor of MyTypedHttpClient takes an instance of HttpClient which is injected by the HttpClientFactory.

Finally, you can use your typed HttpClient in your logic as shown below:

main.cs
public class MyService
{
    private readonly IMyTypedHttpClient _myTypedHttpClient;

    public MyService(IMyTypedHttpClient myTypedHttpClient)
    {
        _myTypedHttpClient = myTypedHttpClient;
    }

    public async Task<string> GetStringFromTypedHttpClient(string url)
    {
        return await _myTypedHttpClient.GetStringAsync(url);
    }
}
352 chars
15 lines

In this example, we are using the IMyTypedHttpClient instance injected via Dependency Injection to call the GetStringAsync method defined on the IMyTypedHttpClient interface.

gistlibby LogSnag