HttpClientFactory how to inject into class I have no control over core 2.1

developer9969 picture developer9969 · Jun 10, 2018 · Viewed 7.2k times · Source

I would like to use the new HttpClientFactory and I am having trouble setting it up.

I have the following (Just noddy examples I put together to explain my point)

public class MyGitHubClient
{
    public MyGitHubClient(HttpClient client)
    {
        Client = client;
    }

    public HttpClient Client { get; }
}

Then in my webapi.Startup I have

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient<MyGitHubClient>(client =>
    {
        client.BaseAddress = new Uri("https://api.github.com/");
       //etc..              
    });

    //NOW I get error "Class name is not valid at this point" for "MyGitHubClient" below

    services.AddSingleton<IThirdPartyService>(x => new ThirdPartyService(MyGitHubClient,someOtherParamHere));

    ///etc...
}

Third party constructor

    public ThirdPartyService(HttpClient httpClient, string anotherParm)
    {

    }       

How can I use the HttpClientFactory when I have to call a class that I have no control over?

Answer

Nkosi picture Nkosi · Jun 10, 2018

The AddSingleton delegate used in the original question takes a IServiceProvider as a parameter argument. Use the provider to resolve the desired dependency

services.AddSingleton<IThirdPartyService>(sp => 
    new ThirdPartyService(sp.GetService<MyGitHubClient>().Client, someOtherParamHere)
);