.NET Framework Version: 4.7.2 Autofac Version: 4.0.1.0
I want to register IHttpClientFactory in my Global.asax but I can't use services.AddHttpClient like in .net core. I need IHttpClientFactory as a dependency for a http client class of my own that I need to reference in my webapi project.
Is this even possible? And if yes, how is it done?
The required component are available in .Net Framework
Create a service collection, invoke add http client extension and use autofac integration Autofac.Extensions.DependencyInjection
to populate your container and get a provider
The following .Net Framework Unit Test is used to demonstrate what was mentioned above
using System;
using System.Net.Http;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
[TestClass]
public class HttpClientFactoryTest {
[TestMethod]
public void Should_Create_HttpClientFactory() {
var services = new ServiceCollection(); //Create a service collection
services.AddHttpClient(); //invoke add http client extension
//...add other services as needed
//use autofac integration `Autofac.Extensions.DependencyInjection`
var providerFactory = new AutofacServiceProviderFactory();
//to populate your container
ContainerBuilder builder = providerFactory.CreateBuilder(services);
//...configure builder as needed
//and get a service provider
IServiceProvider serviceProvider = providerFactory.CreateServiceProvider(builder);
IHttpClientFactory factory = serviceProvider.GetRequiredService<IHttpClientFactory>();
//OR Container
ContainerBuilder builder2 = providerFactory.CreateBuilder(services);
//...configure builder as needed
IContainer container = builder2.Build();
IHttpClientFactory factory2 = container.Resolve<IHttpClientFactory>();
}
}
and be easily reproduced in your Global.asax
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With