From fb649a5c68904f40f849ae15a7d2c909300d19b6 Mon Sep 17 00:00:00 2001 From: Developer 02 Date: Fri, 5 Dec 2025 23:47:28 +0100 Subject: [PATCH] Add static DI-based ReCClient initialization Introduced dependency injection to the `ReCClient` class by adding `Microsoft.Extensions.DependencyInjection`. Added a static mechanism for creating and managing a `ReCClient` instance, including a `BuildStaticClient` method to configure the HTTP client and a `Static` property to retrieve the client. Implemented error handling to ensure proper initialization of the static service provider. --- src/ReC.Client/ReCClient.cs | 40 +++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/ReC.Client/ReCClient.cs b/src/ReC.Client/ReCClient.cs index 4e4bcb8..138bb72 100644 --- a/src/ReC.Client/ReCClient.cs +++ b/src/ReC.Client/ReCClient.cs @@ -1,4 +1,6 @@ using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; + #if NETFRAMEWORK using System; using System.Net.Http; @@ -42,5 +44,43 @@ namespace ReC.Client var resp = _http.PostAsync($"api/RecAction/invoke/{profileId}", content: null).GetAwaiter().GetResult(); return resp.IsSuccessStatusCode; } + + #region Static + private static readonly IServiceCollection Services = new ServiceCollection(); + + private static IServiceProvider +#if nullable + ? +#endif + ServiceProvider +#if nullable + = null +#endif + ; + + public static void BuildStaticClient(string apiUri) + { + if(ServiceProvider != null) + throw new InvalidOperationException("Static ServiceProvider is already built."); + + Services.AddHttpClient(ClientName, client => + { + client.BaseAddress = new Uri(apiUri); + }); + ServiceProvider = Services.BuildServiceProvider(); + } + + public static ReCClient Static + { + get + { + if (ServiceProvider == null) + throw new InvalidOperationException("Static ServiceProvider is not built. Call BuildStaticClient first."); + + var httpClientFactory = ServiceProvider.GetRequiredService(); + return new ReCClient(httpClientFactory); + } + } + #endregion } } \ No newline at end of file