How to configure HttpClient through a Unity container?

I am trying to register an instance of an HttpClient object with a unity container so that it can be used throughout the application, but when run in error - "The HttpMessageHandler type does not have an accessible constructor."

Here is the code I use to register HttpClient with Unity -

private static IUnityContainer BuildUnityContainer()
    {
        var container = new UnityContainer();

        container.RegisterType<HttpClient>(
            new InjectionProperty("BaseAddress", new Uri(ConfigurationManager.AppSettings["ApiUrl"]))); 

        return container;
    }
+5
source share
2 answers

You can use the factory method to register it:

container.RegisterType<HttpClient>(
    new InjectionFactory(x => 
        new HttpClient { BaseAddress = ConfigurationManager.AppSettings["ApiUrl"] }
    )
); 
+4
source

By default, Unity uses the constructor with the most parameters. It will be HttpClient(HttpMessageHandler, Boolean)in your case. You need to explicitly specify the default resultless ctor.

container.RegisterType<HttpClient>(new InjectionProperty(...), new InjectionConstructor());
+9
source

All Articles