Search code examples
c#asp.net-core.net-6.0dotnet-httpclientsystem-design

Best practice to use HttpClient in NET 6.0


I am looking for a best practice solution for the next task.

I use ASP.NET Core 6.0.

I created an SDK which works with public API. The SDK communicates with API via Http request. I use HttpClient class to make http requests.

My goal is to build a Nuget package so consumers will be able to just install this SDK and communicate with the public API.

In the end we have two projects :

  1. Consumer project
  2. SDK project

Question: where do I have to instantiate an instance of HttpClient class?

My thoughts: if I do it in the Sdk project, and just use:

HttpClient client = new HttpClient();

This is not good. Because it is bad practice to create an instance of HttpClient class via new(). See https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines

According this guide from MS, I have to initiate this instance via DI in the consumer project:

services.AddHttpClient(); 

If I select this options I thinks It is will be hard for client to register my SDK, client must do two steps:

  1. Register HttpClient in DI container
  2. Register SDK in container

Is it possible to reduce the amount of steps and make using my library easier?


Solution

  • Without seeing concrete details it is a bit hard to say but you can always reduce the steps to register your library by exposing some kind of AddMySDK method which will handle all the needed registrations including AddHttpClient call, so the end user will have just one call for the default registration:

    public static class MysSDKRegistrationExtensions
    {
        // possibly add another parameter to provide/setup the SDK settings
        public static IServiceCollection AddMySDK(this IServiceCollection services)
        {
            // or add typed ones instead
            services.AddHttpClient(); 
    
            // rest of registrations 
            return services;
        }
    }
    

    Also multiple AddHttpClient calls should not be a problem (if end user will add them in the target app) since internally TryAdd approach is used (see the implementation), i.e. if some needed service was already added to the collection it will not be added again.