13

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;
    }
camelCaseWarrior
  • 369
  • 2
  • 8
  • 19
  • Apparently Unity tries to create the `HttpClient` using the `HttpClient(HttpMessageHandler)` or `HttpClient(HttpMessageHandler, Boolean)` constructor. `HttpMessageHandler` is an abstract class, so it can't create an instance of it. – dtb Feb 04 '13 at 22:46

2 Answers2

12

You can use the factory method to register it instead:

container.RegisterType<HttpClient>(
    new InjectionFactory(x => 
        new HttpClient { BaseAddress = new Uri(ConfigurationManager.AppSettings["ApiUrl"]) }
    )
); 
birwin
  • 2,524
  • 2
  • 21
  • 41
jgauffin
  • 99,844
  • 45
  • 235
  • 372
9

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

container.RegisterType<HttpClient>(
    new InjectionProperty(...), 
    new InjectionConstructor());
ruffin
  • 16,507
  • 9
  • 88
  • 138
Sebastian Weber
  • 6,766
  • 2
  • 30
  • 49
  • Good to know, and it did work. How would we add DefaultRequestHeaders with this InjectionProperty/InjectionConstructor style of configuring? With InjectionFactory it was do-able. – camelCaseWarrior Feb 05 '13 at 17:17
  • @RubberDuckDuck You can add multiple `InjectionProoperties` if you want to. And you can add parameters to the `InjectionConstructor` as well. You have to add all parameters the constructor takes in the correct order. If you want the container to resolve some of those parameters you can add the parameters `Type` as some kind of wildcard. – Sebastian Weber Feb 05 '13 at 19:57