using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ViewEngine.Client.Configuration;
namespace ViewEngine.Client.Extensions;
///
/// Extension methods for registering ViewEngine client services
///
public static class ServiceCollectionExtensions
{
///
/// Adds ViewEngine client services to the dependency injection container
///
/// The service collection
/// The configuration
/// The service collection for chaining
public static IServiceCollection AddViewEngineClient(this IServiceCollection services, IConfiguration configuration)
{
// Bind configuration
services.Configure(configuration.GetSection(ViewEngineOptions.SectionName));
// Register the client as a typed HttpClient
services.AddHttpClient((serviceProvider, httpClient) =>
{
var options = configuration.GetSection(ViewEngineOptions.SectionName).Get()
?? throw new InvalidOperationException("ViewEngine configuration is missing");
if (string.IsNullOrWhiteSpace(options.ApiKey))
throw new InvalidOperationException("ViewEngine API key is required");
httpClient.BaseAddress = new Uri(options.BaseUrl);
httpClient.Timeout = TimeSpan.FromSeconds(options.TimeoutSeconds);
httpClient.DefaultRequestHeaders.Add("X-API-Key", options.ApiKey);
});
return services;
}
///
/// Adds ViewEngine client services to the dependency injection container with custom configuration
///
/// The service collection
/// Action to configure options
/// The service collection for chaining
public static IServiceCollection AddViewEngineClient(this IServiceCollection services, Action configureOptions)
{
// Configure options
services.Configure(configureOptions);
// Register the client as a typed HttpClient
services.AddHttpClient((serviceProvider, httpClient) =>
{
var options = new ViewEngineOptions();
configureOptions(options);
if (string.IsNullOrWhiteSpace(options.ApiKey))
throw new InvalidOperationException("ViewEngine API key is required");
httpClient.BaseAddress = new Uri(options.BaseUrl);
httpClient.Timeout = TimeSpan.FromSeconds(options.TimeoutSeconds);
httpClient.DefaultRequestHeaders.Add("X-API-Key", options.ApiKey);
});
return services;
}
}