using Core.Inventory.External.Clients.Inventory; using Core.Inventory.External.GatewayConfigurations; using Lib.Architecture.BuildingBlocks.Helpers.Token; 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(); // Register ITokenProvider services.AddSingleton(); // Register the custom AuthenticatedHttpClientHandler services.AddTransient(provider => { var tokenProvider = provider.GetRequiredService(); var trackingIdHandler = new TrackingMechanismExtension(provider.GetRequiredService()); var handler = new AuthenticatedHttpClientHandler(tokenProvider) { InnerHandler = new HttpClientHandler() // Setting the InnerHandler manually }; // Attach the TrackingIdHandler as the outermost handler trackingIdHandler.InnerHandler = handler; return handler; }); var inventoryServiceApiUrl = GatewaySettingsConfigurations.GetInventoryServiceAPIEndpoint().Endpoint.Url; // Register IDashBoardServiceClient with the manually created HttpClient services.AddScoped(provider => { var handler = provider.GetRequiredService(); var handlerTrackingId = new TrackingMechanismExtension(provider.GetRequiredService()); // Using the TrackingIdHandler here // Chain the handlers handlerTrackingId.InnerHandler = handler; //chaining var httpClient = new HttpClient(handlerTrackingId) { BaseAddress = new Uri(inventoryServiceApiUrl), Timeout = TimeSpan.FromMinutes(1) }; return RestService.For(httpClient); }); return services; } } }