Files
EnvelopeGenerator/EnvelopeGenerator.Server/EnvelopeGenerator.Server.Client/Services/EnvelopeService.cs
TekH 0763d82f6e 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.
2026-06-28 20:31:30 +02:00

65 lines
2.1 KiB
C#

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(IHttpClientFactory clientFactory)
{
private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);
/// <summary>
/// Fetches envelopes from the API with optional filters.
/// </summary>
/// <exception cref="HttpRequestException">Thrown when the API request fails.</exception>
public async Task<IEnumerable<EnvelopeDto>?> GetAsync(
int? id = null,
string? uuid = null,
bool? onlyActive = null,
bool? onlyCompleted = null,
CancellationToken cancel = default)
{
var baseUrl = $"/api/Envelope";
var queryParams = new Dictionary<string, string?>();
if (id.HasValue)
{
queryParams["Id"] = id.Value.ToString();
}
if (!string.IsNullOrEmpty(uuid))
{
queryParams["Uuid"] = uuid;
}
if (onlyActive.HasValue)
{
queryParams["OnlyActive"] = onlyActive.Value.ToString();
}
if (onlyCompleted.HasValue)
{
queryParams["OnlyCompleted"] = onlyCompleted.Value.ToString();
}
var url = QueryHelpers.AddQueryString(baseUrl, queryParams);
var httpClient = clientFactory.CreateClient("EnvelopeGenerator.Server");
var response = await httpClient.GetAsync(url, cancel);
if (!response.IsSuccessStatusCode)
{
var statusCode = (int)response.StatusCode;
var reasonPhrase = response.ReasonPhrase ?? "Unknown error";
throw new HttpRequestException(
$"Failed to load envelopes. Status: {statusCode} ({reasonPhrase})",
null,
response.StatusCode);
}
return await response.Content.ReadFromJsonAsync<IEnumerable<EnvelopeDto>>(_jsonOptions, cancel);
}
}