// Copyright 2022 Valters Melnalksnis
// Licensed under the Apache License 2.0.
// See LICENSE file in the project root for full license information.
using System;
using System.Net.Http;
using JetBrains.Annotations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using NodaTime;
using VMelnalksnis.NordigenDotNet.Accounts;
using VMelnalksnis.NordigenDotNet.Institutions;
using VMelnalksnis.NordigenDotNet.Requisitions;
namespace VMelnalksnis.NordigenDotNet.DependencyInjection;
/// Collection of methods for configuring VMelnalksnis.NordigenDotNet in .
[PublicAPI]
public static class ServiceCollectionExtensions
{
/// Adds all required services for .
/// The service collection in which to register the services.
/// The configuration to which to bind options models.
/// Time zone provider for date and time serialization.
/// The for the used by .
public static IHttpClientBuilder AddNordigenDotNet(
this IServiceCollection serviceCollection,
IConfiguration configuration,
IDateTimeZoneProvider dateTimeZoneProvider)
{
serviceCollection.TryAddSingleton(dateTimeZoneProvider);
return serviceCollection.AddNordigenDotNet(configuration);
}
/// Adds all required services for , excluding external dependencies.
/// The service collection in which to register the services.
/// The configuration to which to bind options models.
/// The for the used by .
public static IHttpClientBuilder AddNordigenDotNet(
this IServiceCollection serviceCollection,
IConfiguration configuration)
{
serviceCollection
.AddOptions()
.Bind(configuration.GetSection(NordigenOptions.SectionName))
.ValidateDataAnnotations();
return serviceCollection
.AddTransient()
.AddTransient()
.AddTransient()
.AddTransient()
.AddTransient(provider => provider.GetRequiredService>().Value)
.AddHttpClient((provider, client) =>
{
client.BaseAddress = provider.GetRequiredService>().Value.BaseAddress;
var assembly = typeof(INordigenClient).Assembly.GetName();
var assemblyName = assembly.Name ??
throw new InvalidOperationException($"Assembly {assembly.FullName} name is not specified");
var assemblyVersion = assembly.Version ??
throw new InvalidOperationException($"Assembly {assembly.FullName} version is not specified");
client.DefaultRequestHeaders.UserAgent.Add(new(assemblyName, assemblyVersion.ToString()));
});
}
}