using Microsoft.Extensions.DependencyInjection; using OpenWaf.Data; namespace OpenWaf.Infrastructure.Persistence; /// /// Composition of the generated query layer: the driver and the dialect, chosen by /// the same Database:Provider switch that chooses EF's provider. /// /// This is the seam the neighbouring deployment uses the same way — its runtime is /// driver-agnostic over System.Data.Common and Npgsql is supplied at /// composition. Keeping the choice in one place is what lets the same generated /// code serve sqlite (the shipped image) and PostgreSQL (the migrations' provider) /// without either one knowing about the other. /// public static class OpenWafDataComposition { public static IServiceCollection AddOpenWafData(this IServiceCollection services, string provider, string connectionString) { var useSqlite = !provider.Equals("postgres", StringComparison.OrdinalIgnoreCase); services.AddSingleton(_ => useSqlite ? new OrmContext(SqliteDataSource(connectionString), SqliteDialect.Instance) : new OrmContext(PostgresDataSource(connectionString), PostgresDialect.Instance)); return services; } private static System.Data.Common.DbDataSource SqliteDataSource(string connectionString) { // Microsoft.Data.Sqlite needs the native bundle registered before the // first connection opens. EF does this when its sqlite provider is // constructed; a raw data source does not get to assume that happened // first, and the order here is not guaranteed. The call is idempotent. SQLitePCL.Batteries.Init(); return Microsoft.Data.Sqlite.SqliteFactory.Instance.CreateDataSource(connectionString); } private static System.Data.Common.DbDataSource PostgresDataSource(string connectionString) => Npgsql.NpgsqlDataSource.Create(connectionString); }