What is the Difference between IHttpClientFactory and HttpClient

554 views Asked by At

What happens when we create client object using

var client=new HttpClient();

And when we use IHttpClientFactory builder.Services.AddHttpClient();

and using it through Dependency Injection

        public readonly IHttpClientFactory _clientFactory;
        
        public RequestController(ClientPolicy clientPolicy,IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
        }
 
       var client= _clientFactory.CreateClient();

1

There are 1 answers

0
Asad Iftikhar On

The Answer learnt from the above comment and articles is that when an HttpClient is Disposed its socket not disposed so soon that's why it create Socket Exhaustion problem and if we create singleton object of HttpClient then there will be DNS Error that's why in . Net core we implements IHttpClientFactory so it can overcome Socket Exhaustion problem and DNS Problem and its easy to maintain IHttpClientFactory at a single class in case of code modifications it will be implemented