using DocumentService.Client.Configuration;
using DocumentService.Client.Extensions;
using DocumentService.Client.Interfaces;
using DocumentService.Client.Models.ValueObjects;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DocumentService.Client;
///
/// Static entry point for configuring and building the DocumentService client.
///
public static class Client
{
private static Action Options { get; set; } = null!;
private static readonly Lazy LazyProvider = new(() =>
{
var services = new ServiceCollection();
services.AddDocumentServiceClients(Options);
return services.BuildServiceProvider();
});
public static bool IsConfigured => LazyProvider.IsValueCreated;
public static OnReconfigure OnReconfigure { get; set; } = OnReconfigure.ThrowException;
///
/// Configures the client using a full action.
///
/// Action that configures the client options.
public static void Configure(Action configuration)
{
if(IsConfigured)
switch (OnReconfigure)
{
case OnReconfigure.ThrowException:
throw new InvalidOperationException("DocumentService.Client is already configured. Reconfiguration is not allowed.");
case OnReconfigure.Ignore:
return;
}
Options = configuration;
_ = LazyProvider.Value; // init service provider
}
///
/// Configures the client with only a base URL. Use the overload with options action for full control.
///
/// Base URL of the DocumentService API.
public static void Configure(string baseUrl)
{
if (IsConfigured)
switch (OnReconfigure)
{
case OnReconfigure.ThrowException:
throw new InvalidOperationException("DocumentService.Client is already configured. Reconfiguration is not allowed.");
case OnReconfigure.Ignore:
return;
}
Options = options => {
options = new DocumentServiceClientOptions
{
BaseUrl = baseUrl
};
};
_ = LazyProvider.Value; // init service provider
}
private static IServiceProvider Provider => IsConfigured
? LazyProvider.Value
: throw new InvalidOperationException("DocumentService.Client is not configured.");
private static T GetRequiredServiceOfScope() where T : notnull => Provider.CreateAsyncScope().ServiceProvider.GetRequiredService();
#region Controllers
public static IPdfAttachmentClient Attachment => GetRequiredServiceOfScope();
public static IPdfConversionClient Conversion => GetRequiredServiceOfScope();
public static IPdfOperationsClient Operations => GetRequiredServiceOfScope();
public static IPdfValidationClient Validation => GetRequiredServiceOfScope();
public static ISwissQrCodeClient SwissQrCode => GetRequiredServiceOfScope();
public static IZugferdClient Zugferd => GetRequiredServiceOfScope();
#endregion
}