Added CPATapi.Server API Client
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user