Core.Inventory.Service/Core.Inventory.External/ClientConfiguration/RegisterClientConfiguration.cs
2025-06-22 19:34:07 -06:00

59 lines
2.3 KiB
C#

using Core.Inventory.External.Clients;
using Core.Inventory.External.GatewayConfigurations;
using Core.Inventory.External.Helpers;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Refit;
namespace Core.Inventory.External.ClientConfiguration
{
public static class RegisterClientConfiguration
{
public static IServiceCollection RegisterExternalLayer(this IServiceCollection services, IConfiguration configuration)
{
var gatewayConfiguration = new GatewayConfiguration();
var gatewaySettingsConfiguration = new GatewaySettingsConfigurations(configuration);
// Register GatewayConfiguration as a singleton
services.AddSingleton(gatewayConfiguration);
// Register IHttpContextAccessor
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Register ITokenProvider
services.AddSingleton<ITokenProvider, HttpContextTokenProvider>();
// Register the custom AuthenticatedHttpClientHandler
services.AddTransient(provider =>
{
var tokenProvider = provider.GetRequiredService<ITokenProvider>();
var handler = new AuthenticatedHttpClientHandler(tokenProvider)
{
InnerHandler = new HttpClientHandler()
};
return handler;
});
var inventoryServiceApiUrl = GatewaySettingsConfigurations.GetInventoryServiceAPIEndpoint().Endpoint.Url;
// Register IInventoryServiceClient with the manually created HttpClient
services.AddScoped<IInventoryServiceClient>(provider =>
{
var handler = provider.GetRequiredService<AuthenticatedHttpClientHandler>();
var httpClient = new HttpClient(handler)
{
BaseAddress = new Uri(inventoryServiceApiUrl),
Timeout = TimeSpan.FromMinutes(1)
};
return RestService.For<IInventoryServiceClient>(httpClient);
});
services.AddScoped<IAuthenticationService, AuthenticationService>();
return services;
}
}
}