developer9969
developer9969

Reputation: 5216

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

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?

Upvotes: 4

Views: 10316

Answers (2)

George Helyar
George Helyar

Reputation: 5268

In Startup.cs, services.AddHttpClient();

Extension method from https://github.com/dotnet/extensions/blob/master/src/HttpClientFactory/Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs

In your class, add a IHttpClientFactory argument to your constructor.

If you want to use it in a class that doesn't take it, you need to create the HttpClient in a lambda in Add* and pass it in, or register HttpClient itself with that lambda and let DI pass it in

services.AddScoped(s => s.GetRequiredService<IHttpClientFactory>().CreateClient())

There's an example on the project GitHub: https://github.com/dotnet/extensions/blob/master/src/HttpClientFactory/samples/HttpClientFactorySample/Program.cs

Upvotes: 3

Nkosi
Nkosi

Reputation: 246998

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)
);

Upvotes: 3

Related Questions