using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NDB.Infrastructure.DatabaseMigration.Constants; using NDB.Infrastructure.DatabaseMigration.DbContexts; using NDB.Infrastructure.DatabaseMigration.Models; using NDB.Infrastructure.DatabaseMigration.Repositories; using NDB.Infrastructure.DatabaseMigration.Services; using System; namespace NDB.Infrastructure.DatabaseMigration { public static class DependencyInjectionExtensions { private const string _workspacePlaceholder = "{Workspace}"; public static void AddMigration(this IServiceCollection services, DatabaseType databaseType = DatabaseType.SQLite, string connectionName = "DatabaseConnection", string workspace = "Workspace", string scriptsDirectoryPath = "Scripts") { var serviceConfiguration = new ServiceConfiguration(databaseType, connectionName, workspace, scriptsDirectoryPath); services.AddSingleton(serviceConfiguration); services.AddDataAccess(serviceConfiguration); services.AddSingleton(); } private static void AddDataAccess(this IServiceCollection services, ServiceConfiguration serviceConfiguration) { services.AddScoped(); services.AddDbContextPool((serviceProvider, options) => { var connectionString = GetDatabaseConnectionString(serviceProvider, serviceConfiguration.ConnectionName, serviceConfiguration.Workspace); switch (serviceConfiguration.DatabaseType) { case DatabaseType.SQLite: options.UseSqlite(connectionString); break; case DatabaseType.SQLServer: options.UseSqlServer(connectionString); break; default: throw new NotImplementedException($"Database type {serviceConfiguration.DatabaseType} is not implemented."); } }); } private static string GetDatabaseConnectionString(IServiceProvider serviceProvider, string connectionName, string workspace) { var configuration = serviceProvider.GetService(); var connectionString = configuration.GetConnectionString(connectionName); if (connectionString.Contains(_workspacePlaceholder)) { connectionString = connectionString.Replace(_workspacePlaceholder, workspace); } return connectionString; } public static void UseMigration(this IApplicationBuilder app) { var migrationService = app.ApplicationServices.GetService(); migrationService.Execute(); } } }