Refactor services to use IHttpClientFactory
Refactored `DocReceiverElementService` and `EnvelopeService` to use `IHttpClientFactory` instead of directly injecting `HttpClient`, improving flexibility and testability. Updated constructors to accept `IHttpClientFactory` and replaced direct `HttpClient` usage with named clients (`"EnvelopeGenerator.Server"`). Adjusted methods to use the factory-created clients for HTTP requests. Added `using Microsoft.Extensions.Options;` in `Program.cs` and registered `EnvelopeService` and `DocReceiverElementService` in the dependency injection container for proper resolution. Clarified their usage in SSR scenarios with comments. Removed redundant `using` directives and aligned imports with the updated implementation. These changes enhance maintainability, scalability, and testability by leveraging `IHttpClientFactory` for better HTTP client management and dependency injection.
This commit is contained in:
@@ -4,13 +4,15 @@ using EnvelopeGenerator.Server.Client.Models;
|
||||
|
||||
namespace EnvelopeGenerator.Server.Client.Services;
|
||||
|
||||
public class DocReceiverElementService(HttpClient http)
|
||||
public class DocReceiverElementService(IHttpClientFactory clientFactory)
|
||||
{
|
||||
private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
public async Task<IReadOnlyList<SignatureDto>> GetAsync(string envelopeKey, CancellationToken cancel = default)
|
||||
{
|
||||
var url = $"/api/DocReceiverElement/{Uri.EscapeDataString(envelopeKey)}";
|
||||
|
||||
var http = clientFactory.CreateClient("EnvelopeGenerator.Server");
|
||||
var response = await http.GetAsync(url, cancel);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using EnvelopeGenerator.Application.Common.Dto;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace EnvelopeGenerator.Server.Client.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves <see cref="EnvelopeDto"/>s from the API.
|
||||
/// </summary>
|
||||
public class EnvelopeService(HttpClient http)
|
||||
public class EnvelopeService(IHttpClientFactory clientFactory)
|
||||
{
|
||||
private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
||||
@@ -45,7 +46,8 @@ public class EnvelopeService(HttpClient http)
|
||||
|
||||
var url = QueryHelpers.AddQueryString(baseUrl, queryParams);
|
||||
|
||||
var response = await http.GetAsync(url, cancel);
|
||||
var httpClient = clientFactory.CreateClient("EnvelopeGenerator.Server");
|
||||
var response = await httpClient.GetAsync(url, cancel);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user