HttpClientFactory Implementation in MVC specifically in non .Net Core Projects ?


Using of HttpClient is .Net is quite common. Most of the developers do it un-intentionally even without knowing its consequences.

Once your product went too productions and Users start using it, Boom...! the maintenance or devops guys will be in trouble due to the Port exhaustion Issue. If your application is on Cloud, it will cost you so much as resources consumption is more and not only that it will directly affect the performance of your application.

Aaaaah...! One small thing can create such major issues and yes don't forget the escalation from your client.

So, What's the Solution...! Bingo the one which bring you on this blog, the implementation of HttpClientFactory instead of HttpClient. Using DI, HttpClientFactory will only create a single instance and use the same while calling any API unlikely the HttpClient and thus solving your major problems in few seconds. 

It's quite easy when it comes to .Net Core, you have to just add one Library and it starts working. But the major problem will come if your application is built in .Net Framework as there it will not support that library.

So, this blog will provide you to fix the same.

We can do implement HttpClientFactory in .Net mvc, .Net Web API or even in WCF using the following Way :   

Using Unity : 

Unity is an DI framework used to resolve dependency in your application. Mainly it is used in complex applications to resolve the dependency externally.

What we have to Do :

1. Create and Unity Project

2. In the Unity.Config, Register the Class name and Interface where you want to Resolve the dependency.

3. Now go in the Class and Inject HttpClientFactory as DI and create an object. (By using / including Microsoft.Extention library from Nuget package manager.

4. In the code, Write the "ObjectName.CreateClient()", in case of named client you have to write the name in brackets as you mentioned in the Unity Config.

5. Now wherever you are creating the object to call that class method, Resolve the dependency using Resolve Method from Unity Config. This is the main part as without this we can't even call it.

That's it your implementation of HttpClientFactory in MVC or any other Non .Net Core application is done. Will Update the complete process with Code later.

Note : For the WCF Services, It can be only done for Basic Http Binding. And the Ways of creating Request is different which will show later.

Comments

Popular posts from this blog

Border Radius not working in Outlook Email template

C# .Net Core Interview Questions for Freshers and Experienced Developers

15 ways to keep your team motivated while working remotely ?