How to add IHttpClientFactory to NInject in ASP.NET
Asked Answered
S

1

8

I'm trying to add IHttpClientFactory to NInject in my C# ASP.NET Web Forms application so that I can use it in services. There is lots of documentation online about using IHttpClientFactory (and not creating lots of HttpClient instances), however:

  1. Documentation/Examples are based on using the interface with .NET Core and I'm using ASP.NET (i.e. .NET Framework) e.g. https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests, https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.0
  2. Documentation tends to be about wiring up IHttpClientFactory using Microsoft's own dependency injection system rather than NInject.

So, what have I tried? Well, I don't know where to start really as although IHttpClientFactory is well defined in the System.Net.Http namespace, there is no concrete implementation exposed in which I can bind it to. I want to write this:

public class ClassLibNinjectModule : NinjectModule
{
    public override void Load()
    {
        Bind<System.Net.Http.IHttpClientFactory>().ToConstant<System.Net.Http.HttpClientFactory>();
    }
}

However:

  1. System.Net.Http.HttpClientFactory is a static type and it doesn't implement System.Net.Http.IHttpClientFactory (different methods: CreateClient() vs Create())
  2. I can't seem to get how to bind a service to a static provider.

Can anyone advise where I'm going wrong? Thanks.

Spectrophotometer answered 28/11, 2019 at 15:28 Comment(1)
also has this problem. in my project thera are just NinjectModules. There is no startupSulcate
S
3

Install nuget packages:

Microsoft.Extensions.Http
Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.Hosting

Next add to your global.asax.cs:

using Microsoft.Extensions.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace....
....
public static IServiceProvider ServiceProvider;

void Application_Start(object sender, EventArgs e)
{
  var hostBuilder = new HostBuilder();
  hostBuilder.ConfigureServices(ConfigureServices);
  var host = hostBuilder.Build();

  ServiceProvider = host.Services;
}

void ConfigureServices(IServiceCollection services)
{
   services.AddHttpClient(); //extension method that add IHttpClientFactories
   *inject services here*
}
Sulcate answered 5/12, 2019 at 13:49 Comment(3)
Thanks. Does it matter that I'm using a mixture of Microsoft.Extensions.DependencyInjection and Ninject?Spectrophotometer
there are some downsides. Here is some link: #50474799Sulcate
I don't think this answer actually solves the problem of using HttpClientFactory with Ninject. To solve It I recommend this article: hamidmosalla.com/2020/05/22/…Haemolysis

© 2022 - 2024 — McMap. All rights reserved.