1

We are using an older version of Structuremap (3.1.9.463). It's been a while since I used structuremap and HttpClients alongside and I wonter how to properly inject the IHttpClientFactory in structuremap.

Simply using bootStrapper.For<IHttpClientFactory>().Use<HttpClient>(); won't work

A usage example is

public class DialogClient : IDialogClient
{
    private readonly HttpClient _client;

    public DialogClient(IHttpClientFactory httpClientFactory)
    {
        _client = httpClientFactory.CreateClient();
        _client.BaseAddress = new Uri(ConfigurationManager.AppSettings["Dialog:url"]);
    }
}

The project also use .NET Framework, not Core.

Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157

2 Answers2

1

I was able to achieve this in StructureMap with Microsoft.Extensions.Http package.

Having it installed, you can simply register IHttpClientFactory with following code:

var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
configure.For<IHttpClientFactory>().Use(httpClientFactory);

Credit due to simillar issue for Simple Injector: https://github.com/simpleinjector/SimpleInjector/issues/843

Karol Berezicki
  • 652
  • 1
  • 8
  • 14
-1

implement the interface

class MyHttpClientFactory: IHttpClientFactory
{
    public HttpClient CreateClient(string name)
    {
        // logic for creating client here
    }
}

and then register it

For<IHttpClientFactory>().Singleton().Use<MyHttpClientFactory>();