| | | 1 | | using ArturRios.Data.Relational.Core.Configuration; |
| | | 2 | | using ArturRios.Data.Relational.Core.Exceptions; |
| | | 3 | | using ArturRios.Data.Relational.Core.Interfaces; |
| | | 4 | | using ArturRios.Data.Relational.Core.Providers; |
| | | 5 | | using ArturRios.Data.Relational.Core.Repositories; |
| | | 6 | | using ArturRios.Data.Relational.Core.Transactions; |
| | | 7 | | using Microsoft.Extensions.Configuration; |
| | | 8 | | using Microsoft.Extensions.DependencyInjection; |
| | | 9 | | |
| | | 10 | | namespace ArturRios.Data.Relational.Core.DependencyInjection; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// Dependency-injection registration for the ArturRios.Data.Relational.Core relational stack. |
| | | 14 | | /// </summary> |
| | | 15 | | public static class ServiceCollectionExtensions |
| | | 16 | | { |
| | | 17 | | // Best-effort eager check: only throws when it can prove no provider matches. |
| | | 18 | | // Factory-registered providers (services.AddSingleton<IDatabaseProvider>(sp => ...)) expose |
| | | 19 | | // neither ImplementationInstance nor ImplementationType, so TryGetProviderType cannot inspect |
| | | 20 | | // them. Their presence means absence cannot be proven, so validation defers to ResolveProvider |
| | | 21 | | // at first use instead of failing fast on a false negative. |
| | | 22 | | private static void EnsureProviderRegistered(IServiceCollection services, DatabaseType type) |
| | 4 | 23 | | { |
| | 4 | 24 | | var providerTypes = services |
| | 51 | 25 | | .Where(d => d.ServiceType == typeof(IDatabaseProvider)) |
| | 4 | 26 | | .Select(TryGetProviderType) |
| | 4 | 27 | | .ToList(); |
| | | 28 | | |
| | 7 | 29 | | if (providerTypes.Any(t => t == type)) |
| | 2 | 30 | | { |
| | 2 | 31 | | return; |
| | | 32 | | } |
| | | 33 | | |
| | 3 | 34 | | var hasUninspectableProvider = providerTypes.Any(t => t is null); |
| | | 35 | | |
| | 2 | 36 | | if (hasUninspectableProvider) |
| | 1 | 37 | | { |
| | 1 | 38 | | return; |
| | | 39 | | } |
| | | 40 | | |
| | 1 | 41 | | throw new DataAccessException( |
| | 1 | 42 | | [ |
| | 1 | 43 | | $"No IDatabaseProvider registered for DatabaseType '{type}'. " + |
| | 1 | 44 | | $"Install and register the matching provider package " + |
| | 1 | 45 | | $"(e.g. ArturRios.Data.Core.{type}) by calling its Add{type}Provider() extension." |
| | 1 | 46 | | ]); |
| | 3 | 47 | | } |
| | | 48 | | |
| | | 49 | | // Reads a registered provider's DatabaseType without building a ServiceProvider. |
| | | 50 | | // Providers are stateless with parameterless constructors, so instantiating to read Type is safe. |
| | | 51 | | private static DatabaseType? TryGetProviderType(ServiceDescriptor descriptor) |
| | 3 | 52 | | { |
| | 3 | 53 | | if (descriptor.ImplementationInstance is IDatabaseProvider instance) |
| | 2 | 54 | | { |
| | 2 | 55 | | return instance.Type; |
| | | 56 | | } |
| | | 57 | | |
| | 1 | 58 | | if (descriptor.ImplementationType is { } implementationType && |
| | 1 | 59 | | Activator.CreateInstance(implementationType) is IDatabaseProvider created) |
| | 0 | 60 | | { |
| | 0 | 61 | | return created.Type; |
| | | 62 | | } |
| | | 63 | | |
| | 1 | 64 | | return null; |
| | 3 | 65 | | } |
| | | 66 | | |
| | | 67 | | private static IDatabaseProvider ResolveProvider( |
| | | 68 | | IEnumerable<IDatabaseProvider> providers, DatabaseType type) |
| | 3 | 69 | | { |
| | 6 | 70 | | var match = providers.FirstOrDefault(p => p.Type == type); |
| | 3 | 71 | | if (match is null) |
| | 0 | 72 | | { |
| | 0 | 73 | | throw new DataAccessException( |
| | 0 | 74 | | [ |
| | 0 | 75 | | $"No IDatabaseProvider registered for DatabaseType '{type}'. " + |
| | 0 | 76 | | $"Install and register the matching provider package " + |
| | 0 | 77 | | $"(e.g. ArturRios.Data.Core.{type}) by calling its Add{type}Provider() extension." |
| | 0 | 78 | | ]); |
| | | 79 | | } |
| | | 80 | | |
| | 3 | 81 | | return match; |
| | 3 | 82 | | } |
| | | 83 | | |
| | | 84 | | /// <param name="services">The service collection.</param> |
| | | 85 | | extension(IServiceCollection services) |
| | | 86 | | { |
| | | 87 | | /// <summary> |
| | | 88 | | /// Registers the configured <typeparamref name="TContext" />, repositories, and unit of work, |
| | | 89 | | /// binding options from the given configuration section. |
| | | 90 | | /// </summary> |
| | | 91 | | /// <param name="configuration">Application configuration.</param> |
| | | 92 | | /// <param name="sectionName">Configuration section holding the options.</param> |
| | | 93 | | /// <typeparam name="TContext">The application's context type.</typeparam> |
| | | 94 | | public IServiceCollection AddDataConfigFromSettings<TContext>(IConfiguration configuration, |
| | | 95 | | string sectionName) |
| | | 96 | | where TContext : BaseDbContext |
| | 0 | 97 | | { |
| | 0 | 98 | | var options = configuration.GetSection(sectionName).Get<BaseDbContextOptions>() |
| | 0 | 99 | | ?? new BaseDbContextOptions(); |
| | | 100 | | |
| | 0 | 101 | | return services.AddDataConfig<TContext>(options); |
| | | 102 | | } |
| | | 103 | | |
| | | 104 | | /// <summary> |
| | | 105 | | /// Registers the configured <typeparamref name="TContext" />, repositories, and unit of work |
| | | 106 | | /// from an explicit options instance. |
| | | 107 | | /// </summary> |
| | | 108 | | /// <param name="options">The database options.</param> |
| | | 109 | | /// <typeparam name="TContext">The application's context type.</typeparam> |
| | | 110 | | public IServiceCollection AddDataConfig<TContext>(BaseDbContextOptions options) |
| | | 111 | | where TContext : BaseDbContext |
| | 4 | 112 | | { |
| | 4 | 113 | | services.AddDbContext<TContext>((sp, builder) => |
| | 3 | 114 | | { |
| | 3 | 115 | | var provider = ResolveProvider(sp.GetServices<IDatabaseProvider>(), options.DatabaseType); |
| | 3 | 116 | | provider.Configure(builder, options.ConnectionString); |
| | 7 | 117 | | }); |
| | | 118 | | |
| | 7 | 119 | | services.AddScoped<BaseDbContext>(sp => sp.GetRequiredService<TContext>()); |
| | | 120 | | |
| | 4 | 121 | | services.AddScoped(typeof(IReadOnlyRepository<>), typeof(EfRepository<>)); |
| | 4 | 122 | | services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>)); |
| | 4 | 123 | | services.AddScoped(typeof(IAsyncReadOnlyRepository<>), typeof(EfRepository<>)); |
| | 4 | 124 | | services.AddScoped(typeof(IAsyncRepository<>), typeof(EfRepository<>)); |
| | | 125 | | |
| | 4 | 126 | | services.AddScoped<IUnitOfWork, EfUnitOfWork>(); |
| | 4 | 127 | | services.AddScoped<IAsyncUnitOfWork, EfUnitOfWork>(); |
| | | 128 | | |
| | | 129 | | // Validate provider availability eagerly so misconfiguration fails at registration, not first use. |
| | 4 | 130 | | EnsureProviderRegistered(services, options.DatabaseType); |
| | | 131 | | |
| | 3 | 132 | | return services; |
| | | 133 | | } |
| | | 134 | | |
| | | 135 | | /// <summary> |
| | | 136 | | /// Registers the configured <typeparamref name="TContext" />, repositories, and unit of work, |
| | | 137 | | /// reading options entirely from environment variables. The appsettings section is not consulted. |
| | | 138 | | /// </summary> |
| | | 139 | | /// <param name="prefix"> |
| | | 140 | | /// Environment-variable name prefix. Variables are read as |
| | | 141 | | /// <c>{prefix}_DATABASETYPE</c> and <c>{prefix}_CONNECTIONSTRING</c>. |
| | | 142 | | /// </param> |
| | | 143 | | /// <typeparam name="TContext">The application's context type.</typeparam> |
| | | 144 | | public IServiceCollection AddDataConfigFromEnvironment<TContext>(string prefix) |
| | | 145 | | where TContext : BaseDbContext |
| | 8 | 146 | | { |
| | 8 | 147 | | if (string.IsNullOrWhiteSpace(prefix)) |
| | 3 | 148 | | { |
| | 3 | 149 | | throw new ArgumentException( |
| | 3 | 150 | | "Environment-variable prefix must not be null or whitespace.", nameof(prefix)); |
| | | 151 | | } |
| | | 152 | | |
| | 5 | 153 | | var databaseTypeValue = Environment.GetEnvironmentVariable($"{prefix}_DATABASETYPE"); |
| | | 154 | | |
| | 5 | 155 | | if (!Enum.TryParse<DatabaseType>(databaseTypeValue, ignoreCase: true, out var databaseType) || |
| | 5 | 156 | | !Enum.IsDefined(databaseType)) |
| | 4 | 157 | | { |
| | 4 | 158 | | throw new DataAccessException( |
| | 4 | 159 | | [ |
| | 4 | 160 | | $"Environment variable '{prefix}_DATABASETYPE' is unset or not a valid DatabaseType. " + |
| | 4 | 161 | | $"Allowed values: {string.Join(", ", Enum.GetNames<DatabaseType>())}." |
| | 4 | 162 | | ]); |
| | | 163 | | } |
| | | 164 | | |
| | 1 | 165 | | var connectionString = |
| | 1 | 166 | | Environment.GetEnvironmentVariable($"{prefix}_CONNECTIONSTRING") ?? string.Empty; |
| | | 167 | | |
| | 1 | 168 | | return services.AddDataConfig<TContext>(new BaseDbContextOptions |
| | 1 | 169 | | { |
| | 1 | 170 | | DatabaseType = databaseType, |
| | 1 | 171 | | ConnectionString = connectionString |
| | 1 | 172 | | }); |
| | | 173 | | } |
| | | 174 | | } |
| | | 175 | | } |