Search code examples
c#.netunity-containerasp.net-web-api

How to configure HttpClient via Unity container?


I'm trying to register an instance of HttpClient object with the unity container so that it can be used throughout the app, but running into the error - "The type HttpMessageHandler does not have an accessible constructor."

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

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

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

        return container;
    }

Solution

  • You can use the factory method to register it instead:

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