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.
This commit is contained in:
parent
f4abac1103
commit
fb649a5c68
@ -1,4 +1,6 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
#if NETFRAMEWORK
|
#if NETFRAMEWORK
|
||||||
using System;
|
using System;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
@ -42,5 +44,43 @@ namespace ReC.Client
|
|||||||
var resp = _http.PostAsync($"api/RecAction/invoke/{profileId}", content: null).GetAwaiter().GetResult();
|
var resp = _http.PostAsync($"api/RecAction/invoke/{profileId}", content: null).GetAwaiter().GetResult();
|
||||||
return resp.IsSuccessStatusCode;
|
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<IHttpClientFactory>();
|
||||||
|
return new ReCClient(httpClientFactory);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user