Menu

ASP.NET Core C# API – Register a service dependency that uses HttpClient correctly

More often we have to call a RESTfull service, it could be simple as sending an email, SMS, posting a message, etc. We use can use an HttpClient for all our HTTP calls. Alternatively, we can use a library such as Restshaper.

In this sample service, we will be dependency injecting the HttpClient, so it can be used for Unit testing.

Service going to be simple

public class IntegrationService : IIntegrationService
{
   private readonly HttpClient _client;

   public IntegrationService(HttpClient client)
   {
      _client = client;
   }

   public async Task<bool> Notify<T>(MessageEnvelope<T> message)
   {
      using (var request = new HttpRequestMessage())
      {
         request.Method = HttpMethod.Post;
         request.Content = new StringContent(JsonConvert.SerializeObject(message));
         request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

         var response = await _client.SendAsync(request);

         var responseContent = await response.Content.ReadAsStringAsync();

         return true; // your real output, as per your actual implimentation
      }
   }
}

As part of your Startup.cs we need to register our awesome service under “ConfigureServices“, like below

public void ConfigureServices(IServiceCollection services)
{
   services.AddMediatR(typeof(.....).Assembly);

   services.AddHttpClient<IIntegrationService, IntegrationService>("IntegrationService", client =>
   {
      client.BaseAddress = new Uri("https://api/integration-endpoint");
   });

   services.AddControllers()
      .AddNewtonsoftJson(x =>
      {
         x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
      });
   .....
   .....
}

When you implement this way it improves efficiency, managing the lifetime, avoid any DNS issues.

Leave a comment