| | | 1 | | namespace Envilder.Infrastructure.DependencyInjection; |
| | | 2 | | |
| | | 3 | | using Envilder.Application; |
| | | 4 | | using Envilder.Domain; |
| | | 5 | | using Envilder.Domain.Ports; |
| | | 6 | | using Microsoft.Extensions.DependencyInjection; |
| | | 7 | | using System; |
| | | 8 | | using System.IO; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Extension methods for registering Envilder services in an |
| | | 12 | | /// <see cref="IServiceCollection"/> dependency injection container. |
| | | 13 | | /// </summary> |
| | | 14 | | public static class ServiceCollectionExtensions |
| | | 15 | | { |
| | | 16 | | /// <summary> |
| | | 17 | | /// Parses the map file at <paramref name="mapFilePath"/>, creates an |
| | | 18 | | /// <see cref="EnvilderClient"/> backed by <paramref name="secretProvider"/>, |
| | | 19 | | /// and registers both the client and the parsed <see cref="ParsedMapFile"/> |
| | | 20 | | /// as singleton services. |
| | | 21 | | /// </summary> |
| | | 22 | | /// <param name="services">The service collection.</param> |
| | | 23 | | /// <param name="mapFilePath">Path to the JSON map file on disk.</param> |
| | | 24 | | /// <param name="secretProvider">The secret provider to resolve values from.</param> |
| | | 25 | | /// <returns>The same <see cref="IServiceCollection"/> for chaining.</returns> |
| | | 26 | | /// <exception cref="ArgumentException"><paramref name="mapFilePath"/> is null or empty.</exception> |
| | | 27 | | /// <exception cref="FileNotFoundException">The map file does not exist on disk.</exception> |
| | | 28 | | public static IServiceCollection AddEnvilder(this IServiceCollection services, |
| | | 29 | | string mapFilePath, |
| | | 30 | | ISecretProvider secretProvider) |
| | | 31 | | { |
| | 1 | 32 | | if (string.IsNullOrWhiteSpace(mapFilePath)) |
| | | 33 | | { |
| | 1 | 34 | | throw new ArgumentException("Map file path cannot be null or empty.", nameof(mapFilePath)); |
| | | 35 | | } |
| | | 36 | | |
| | 1 | 37 | | if (!File.Exists(mapFilePath)) |
| | | 38 | | { |
| | 1 | 39 | | throw new FileNotFoundException("Map file not found.", mapFilePath); |
| | | 40 | | } |
| | | 41 | | |
| | 1 | 42 | | if (secretProvider is null) |
| | | 43 | | { |
| | 1 | 44 | | throw new ArgumentNullException(nameof(secretProvider)); |
| | | 45 | | } |
| | | 46 | | |
| | 1 | 47 | | var json = File.ReadAllText(mapFilePath); |
| | 1 | 48 | | var mapFile = new MapFileParser().Parse(json); |
| | | 49 | | |
| | 1 | 50 | | services.AddSingleton(mapFile); |
| | 1 | 51 | | services.AddSingleton(new EnvilderClient(secretProvider)); |
| | | 52 | | |
| | 1 | 53 | | return services; |
| | | 54 | | } |
| | | 55 | | } |