netmash/infrastructure/Netmash.Infrastructure.Data.../DependencyInjectionExtensio...

77 lines
3.4 KiB
C#

using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Netmash.Infrastructure.DatabaseMigration.Constants;
using Netmash.Infrastructure.DatabaseMigration.DbContexts;
using Netmash.Infrastructure.DatabaseMigration.Models;
using Netmash.Infrastructure.DatabaseMigration.Repositories;
using Netmash.Infrastructure.DatabaseMigration.Services;
using Netmash.Infrastructure.DatabaseMigration.Services.Abstractions;
using System;
namespace Netmash.Infrastructure.DatabaseMigration
{
public static class DependencyInjectionExtensions
{
private const string _workspacePlaceholder = "{Workspace}";
public static void AddMigration(this IServiceCollection services,
DatabaseType databaseType = DatabaseType.SQLite,
MetadataLocation metadataLocation = MetadataLocation.XmlFile,
string connectionName = "DatabaseConnection",
string workspace = "Workspace",
string scriptsDirectoryPath = "Scripts")
{
var serviceConfiguration = new ServiceConfiguration(databaseType, metadataLocation, connectionName, workspace, scriptsDirectoryPath);
services.AddSingleton(serviceConfiguration);
services.AddDataAccess(serviceConfiguration);
services.AddSingleton<IMetadataLocationService, MetadataLocationService>();
services.AddSingleton<IMigrationSignaturesService, MigrationSignaturesService>();
services.AddSingleton<IMigrationService, MigrationService>();
}
private static void AddDataAccess(this IServiceCollection services, ServiceConfiguration serviceConfiguration)
{
services.AddScoped<IMigrationRepository, MigrationRepository>();
services.AddDbContextPool<MigrationDbContext>((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<IConfiguration>();
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<IMigrationService>();
migrationService.Execute();
}
}
}