1

I have built a command-line app using .net core 3.0 using the Generic Host Builder. If I add a HttpClient to the services using AddHttpClient the the service requesting HttpClient fails to resolve with an error "Unable to resolve service for type 'System.Net.Http.HttpClient'"

If I register HttpClient myself then it resolves, so it appears that the AddHttpClient does not work unless it is a Http Server.

I find the whole AddHttpClient approach a bit more attractive as I can easily add policies etc. In fact I am trying to create a reusable component that I can share between applications(web and non-web) which builds a consistent HttpClient.

Building Host

        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHttpClient(); // This fails to resolve HttpClient
                //services.AddSingleton<HttpClient>(provider => new HttpClient());    //This resolves okay
                services.AddSingleton<TestClass>();
            });

Classes requiring HttpClient which fail to resolve

    public class TestClass : ITestClass
{
    public TestClass(HttpClient client)
    {

    }
}

public interface ITestClass
{
}
1
  • You are looking for a typed client. AddHttpClient just adds the factory Commented Oct 16, 2019 at 18:39

1 Answer 1

1

AddHttpClient just adds the factory

You are looking for a typed client.

//...
.ConfigureServices((hostContext, services) => {
    services.AddHttpClient<ITestClass, TestClass>();

})
//...
Sign up to request clarification or add additional context in comments.

1 Comment

apologies, may of misunderstood your answer, if I add your line to my solution then that works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.