Files
3cx_tapi/server/src/CPATapi.Client/ServiceExtensions.cs
T

54 lines
1.8 KiB
C#
Raw Normal View History

2026-04-09 14:12:21 +02:00
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Kiota.Abstractions.Authentication;
using Microsoft.Kiota.Http.HttpClientLibrary;
namespace CPATapi.Client;
public static class ServiceExtensions
{
public static IServiceCollection AddCPATapiClient(this IServiceCollection services, Action<IServiceProvider, HttpClient> configureOptions)
{
services.AddKiotaHandlers();
services.AddHttpClient<CPATapiClientFactory>((sp, client) =>
{
configureOptions.Invoke(sp, client);
}).AttachKiotaHandlers();
services.AddTransient(sp => sp.GetRequiredService<CPATapiClientFactory>().GetClient());
return services;
}
private static IServiceCollection AddKiotaHandlers(this IServiceCollection services)
{
var handlers = KiotaClientFactory.GetDefaultHandlerActivatableTypes();
foreach (var handler in handlers)
{
if (services.All(s => s.ServiceType != handler))
{
services.AddScoped(handler);
}
}
return services;
}
private static IHttpClientBuilder AttachKiotaHandlers(this IHttpClientBuilder builder)
{
var handlers = KiotaClientFactory.GetDefaultHandlerActivatableTypes();
foreach (var handler in handlers)
{
builder.AddHttpMessageHandler((sp) => (DelegatingHandler)sp.GetRequiredService(handler));
}
return builder;
}
}
internal class CPATapiClientFactory(HttpClient httpClient)
{
private readonly HttpClient _httpClient = httpClient;
private readonly AnonymousAuthenticationProvider _authenticationProvider = new();
public CPATapiClient GetClient()
{
return new CPATapiClient(new HttpClientRequestAdapter(_authenticationProvider, httpClient: _httpClient));
}
}