feat: 先搞一个dbmigrator凑合用

This commit is contained in:
2025-10-25 16:06:23 +08:00
parent ab8f120366
commit 283c30310a
17 changed files with 290 additions and 58 deletions

View File

@ -193,6 +193,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KonSoft.Shared.Hosting.Gate
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KonSoft.Shared.Hosting.Microservices", "shared\KonSoft.Shared.Hosting.Microservices\KonSoft.Shared.Hosting.Microservices.csproj", "{ADF28580-F8A0-4495-96D6-736C6C7CF3FF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KonSoft.Shared.DbMigrator", "shared\KonSoft.Shared.DbMigrator\KonSoft.Shared.DbMigrator.csproj", "{AFCC65BC-8477-819B-2575-674AC9D2FDDD}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -499,6 +501,10 @@ Global
{ADF28580-F8A0-4495-96D6-736C6C7CF3FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ADF28580-F8A0-4495-96D6-736C6C7CF3FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ADF28580-F8A0-4495-96D6-736C6C7CF3FF}.Release|Any CPU.Build.0 = Release|Any CPU
{AFCC65BC-8477-819B-2575-674AC9D2FDDD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AFCC65BC-8477-819B-2575-674AC9D2FDDD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AFCC65BC-8477-819B-2575-674AC9D2FDDD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AFCC65BC-8477-819B-2575-674AC9D2FDDD}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -594,6 +600,7 @@ Global
{8CA6B487-3AAF-4E77-ACE0-01D878DE4836} = {7EFFD2C6-2041-4967-A715-0F817D70C433}
{BBB1A129-9ED7-4F08-B710-B6C287197BFB} = {7EFFD2C6-2041-4967-A715-0F817D70C433}
{ADF28580-F8A0-4495-96D6-736C6C7CF3FF} = {7EFFD2C6-2041-4967-A715-0F817D70C433}
{AFCC65BC-8477-819B-2575-674AC9D2FDDD} = {7EFFD2C6-2041-4967-A715-0F817D70C433}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {28315BFD-90E7-4E14-A2EA-F3D23AF4126F}

View File

@ -21,4 +21,5 @@
<s:String x:Key="/Default/CodeStyle/Generate/=Overrides/Options/=Mutable/@EntryIndexedValue">False</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SQL/@EntryIndexedValue">SQL</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Consts/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Iddict/@EntryIndexedValue">True</s:Boolean>
</wpf:ResourceDictionary>

View File

@ -60,7 +60,7 @@ public class KonSoftAuthServerModule : AbpModule
PreConfigure<OpenIddictServerBuilder>(serverBuilder =>
{
serverBuilder.AddProductionEncryptionAndSigningCertificate("openiddict.pfx",
configuration["Certificate:Password"]);
"59464dba-b66e-48cd-8b81-2e4a9c08c977");
});
}
}

View File

@ -1,8 +0,0 @@
using System.Threading.Tasks;
namespace KonSoft.Admin.Data;
public interface IAdminDbSchemaMigrator
{
Task MigrateAsync();
}

View File

@ -1,15 +0,0 @@
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
namespace KonSoft.Admin.Data;
/* This is used if database provider does't define
* IAdminDbSchemaMigrator implementation.
*/
public class NullAdminDbSchemaMigrator : IAdminDbSchemaMigrator, ITransientDependency
{
public Task MigrateAsync()
{
return Task.CompletedTask;
}
}

View File

@ -13,19 +13,19 @@ using Volo.Abp.Identity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.TenantManagement;
namespace KonSoft.Admin.Data;
namespace KonSoft.Shared.DbMigrator.Data;
public class AdminDbMigrationService : ITransientDependency
public class DbMigrationService : ITransientDependency
{
private readonly ICurrentTenant _currentTenant;
private readonly IDataSeeder _dataSeeder;
private readonly IEnumerable<IAdminDbSchemaMigrator> _dbSchemaMigrators;
private readonly IEnumerable<IDbSchemaMigrator> _dbSchemaMigrators;
private readonly ITenantRepository _tenantRepository;
public AdminDbMigrationService(
public DbMigrationService(
IDataSeeder dataSeeder,
IEnumerable<IAdminDbSchemaMigrator> dbSchemaMigrators,
IEnumerable<IDbSchemaMigrator> dbSchemaMigrators,
ITenantRepository tenantRepository,
ICurrentTenant currentTenant)
{
@ -34,10 +34,10 @@ public class AdminDbMigrationService : ITransientDependency
_tenantRepository = tenantRepository;
_currentTenant = currentTenant;
Logger = NullLogger<AdminDbMigrationService>.Instance;
Logger = NullLogger<DbMigrationService>.Instance;
}
public ILogger<AdminDbMigrationService> Logger { get; set; }
public ILogger<DbMigrationService> Logger { get; set; }
public async Task MigrateAsync()
{

View File

@ -1,18 +1,18 @@
using System;
using System.Threading.Tasks;
using KonSoft.Admin.Data;
using KonSoft.Admin.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.DependencyInjection;
namespace KonSoft.Admin.EntityFrameworkCore;
namespace KonSoft.Shared.DbMigrator.Data;
public class EntityFrameworkCoreAdminDbSchemaMigrator
: IAdminDbSchemaMigrator, ITransientDependency
public class EntityFrameworkCoreDbSchemaMigrator
: IDbSchemaMigrator, ITransientDependency
{
private readonly IServiceProvider _serviceProvider;
public EntityFrameworkCoreAdminDbSchemaMigrator(
public EntityFrameworkCoreDbSchemaMigrator(
IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;

View File

@ -0,0 +1,8 @@
using System.Threading.Tasks;
namespace KonSoft.Shared.DbMigrator.Data;
public interface IDbSchemaMigrator
{
Task MigrateAsync();
}

View File

@ -0,0 +1,51 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using System.Threading;
using System.Threading.Tasks;
using KonSoft.Shared.DbMigrator.Data;
using Volo.Abp;
using Volo.Abp.Data;
namespace KonSoft.Shared.DbMigrator;
public class DbMigratorHostedService : IHostedService
{
private readonly IHostApplicationLifetime _hostApplicationLifetime;
private readonly IConfiguration _configuration;
public DbMigratorHostedService(IHostApplicationLifetime hostApplicationLifetime, IConfiguration configuration)
{
_hostApplicationLifetime = hostApplicationLifetime;
_configuration = configuration;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
using (var application = await AbpApplicationFactory.CreateAsync<KonSoftSharedDbMigratorModule>(options =>
{
options.Services.ReplaceConfiguration(_configuration);
options.UseAutofac();
options.Services.AddLogging(c => c.AddSerilog());
options.AddDataMigrationEnvironment();
}))
{
await application.InitializeAsync();
await application
.ServiceProvider
.GetRequiredService<DbMigrationService>()
.MigrateAsync();
await application.ShutdownAsync();
_hostApplicationLifetime.StopApplication();
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}

View File

@ -0,0 +1,26 @@
FROM mcr.microsoft.com/dotnet/runtime:9.0 AS base
USER $APP_UID
WORKDIR /app
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
ARG BUILD_CONFIGURATION=Release
COPY ["./common.props", "."]
COPY ["./NuGet.Config", "."]
COPY ["./src/KonSoft.SnowClub.DbMigrator/KonSoft.SnowClub.DbMigrator.csproj", "KonSoft.SnowClub.DbMigrator/"]
COPY ["./src/KonSoft.SnowClub.Application.Contracts/KonSoft.SnowClub.Application.Contracts.csproj", "KonSoft.SnowClub.Application.Contracts/"]
COPY ["./src/KonSoft.SnowClub.Domain.Shared/KonSoft.SnowClub.Domain.Shared.csproj", "KonSoft.SnowClub.Domain.Shared/"]
COPY ["./src/KonSoft.SnowClub.EntityFrameworkCore/KonSoft.SnowClub.EntityFrameworkCore.csproj", "KonSoft.SnowClub.EntityFrameworkCore/"]
COPY ["./src/KonSoft.SnowClub.Domain/KonSoft.SnowClub.Domain.csproj", "KonSoft.SnowClub.Domain/"]
RUN dotnet restore "./KonSoft.SnowClub.DbMigrator/KonSoft.SnowClub.DbMigrator.csproj"
COPY . .
WORKDIR "/src/KonSoft.SnowClub.DbMigrator"
RUN dotnet build "./KonSoft.SnowClub.DbMigrator.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./KonSoft.SnowClub.DbMigrator.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "KonSoft.SnowClub.DbMigrator.dll"]

View File

@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
<Content Include="appsettings.json">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\modules\admin\src\KonSoft.Admin.Application.Contracts\KonSoft.Admin.Application.Contracts.csproj" />
<ProjectReference Include="..\..\modules\admin\src\KonSoft.Admin.EntityFrameworkCore\KonSoft.Admin.EntityFrameworkCore.csproj" />
<ProjectReference Include="..\KonSoft.Shared.Hosting.AspNetCore\KonSoft.Shared.Hosting.AspNetCore.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Remove="Logs\**" />
<Content Remove="Logs\**" />
<EmbeddedResource Remove="Logs\**" />
<None Remove="Logs\**" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,20 @@
using KonSoft.Admin;
using KonSoft.Admin.EntityFrameworkCore;
using KonSoft.Shared.Hosting;
using Volo.Abp.Caching;
using Volo.Abp.Modularity;
namespace KonSoft.Shared.DbMigrator;
[DependsOn(
typeof(KonSoftSharedHostingModule),
typeof(AdminEntityFrameworkCoreModule),
typeof(AdminApplicationContractsModule)
)]
public class KonSoftSharedDbMigratorModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
Configure<AbpDistributedCacheOptions>(options => { options.KeyPrefix = "KonSoft:"; });
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace KonSoft.Shared.DbMigrator.OpenIddict
{
public class OpenIddictApplicationOptions
{
public string Name { get; set; }
public string Type { get; set; }
public string ConsentType { get; set; }
public string DisplayName { get; set; }
public string? Secret { get; set; }
public List<string> GrantTypes { get; set; }
public string? PostLogoutRedirectUri { get; set; }
}
}

View File

@ -16,7 +16,7 @@ using Volo.Abp.OpenIddict.Scopes;
using Volo.Abp.PermissionManagement;
using Volo.Abp.Uow;
namespace KonSoft.Admin.OpenIddict;
namespace KonSoft.Shared.DbMigrator.OpenIddict;
/* Creates initial data that is needed to property run the application
* and make client-to-server communication possible.
@ -62,7 +62,49 @@ public class OpenIddictDataSeedContributor : IDataSeedContributor, ITransientDep
{
await _scopeManager.CreateAsync(new OpenIddictScopeDescriptor
{
Name = "Admin", DisplayName = "Admin API", Resources = { "Admin" }
Name = "Admin",
DisplayName = "Admin API",
Resources = { "Admin" }
});
}
if (await _openIddictScopeRepository.FindByNameAsync("Dispatch") == null)
{
await _scopeManager.CreateAsync(new OpenIddictScopeDescriptor
{
Name = "Dispatch",
DisplayName = "Dispatch API",
Resources = { "Dispatch" }
});
}
if (await _openIddictScopeRepository.FindByNameAsync("Payment") == null)
{
await _scopeManager.CreateAsync(new OpenIddictScopeDescriptor
{
Name = "Payment",
DisplayName = "Payment API",
Resources = { "Payment" }
});
}
if (await _openIddictScopeRepository.FindByNameAsync("Report") == null)
{
await _scopeManager.CreateAsync(new OpenIddictScopeDescriptor
{
Name = "Report",
DisplayName = "Report API",
Resources = { "Report" }
});
}
if (await _openIddictScopeRepository.FindByNameAsync("TenantManagement") == null)
{
await _scopeManager.CreateAsync(new OpenIddictScopeDescriptor
{
Name = "TenantManagement",
DisplayName = "TenantManagement API",
Resources = { "TenantManagement" }
});
}
}
@ -76,29 +118,20 @@ public class OpenIddictDataSeedContributor : IDataSeedContributor, ITransientDep
OpenIddictConstants.Permissions.Scopes.Phone,
OpenIddictConstants.Permissions.Scopes.Profile,
OpenIddictConstants.Permissions.Scopes.Roles,
"Admin"
"Admin",
"Dispatch",
"Payment",
"Report",
"TenantManagement"
};
var configurationSection = _configuration.GetSection("OpenIddict:Applications");
// Swagger Client
var swaggerClientId = configurationSection["Admin_Swagger:ClientId"];
if (!swaggerClientId.IsNullOrWhiteSpace())
var apps = new List<OpenIddictApplicationOptions>();
_configuration.GetSection("OpenIddict:Applications").Bind(apps);
foreach (var openIddictApplication in apps)
{
var swaggerRootUrl = configurationSection["Admin_Swagger:RootUrl"]?.TrimEnd('/');
await CreateApplicationAsync(
swaggerClientId!,
OpenIddictConstants.ClientTypes.Public,
OpenIddictConstants.ConsentTypes.Implicit,
"Swagger Application",
null,
[OpenIddictConstants.GrantTypes.AuthorizationCode],
commonScopes,
redirectUri: $"{swaggerRootUrl}/swagger/oauth2-redirect.html",
clientUri: swaggerRootUrl
);
await CreateApplicationAsync(openIddictApplication.Name, openIddictApplication.Type,
openIddictApplication.ConsentType, openIddictApplication.DisplayName, openIddictApplication.Secret,
openIddictApplication.GrantTypes, commonScopes, openIddictApplication.PostLogoutRedirectUri);
}
}

View File

@ -0,0 +1,44 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using System;
using System.Threading.Tasks;
namespace KonSoft.Shared.DbMigrator;
class Program
{
static async Task Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Volo.Abp", LogEventLevel.Warning)
#if DEBUG
.MinimumLevel.Override("KonSoft.Clean", LogEventLevel.Debug)
#else
.MinimumLevel.Override("KonSoft.Clean", LogEventLevel.Information)
#endif
.Enrich.FromLogContext()
.WriteTo.Async(c => c.File("Logs/logs.txt"))
.WriteTo.Async(c => c.Console())
.CreateLogger();
await CreateHostBuilder(args).RunConsoleAsync();
}
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseAgileConfig(options =>
{
options.ENV = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
})
.AddAppSettingsSecretsJson()
.ConfigureLogging((context, logging) => logging.ClearProviders())
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<DbMigratorHostedService>();
});
}

View File

@ -0,0 +1,7 @@
{
"profiles": {
"KonSoft.SnowClub.DbMigrator": {
"commandName": "Project"
}
}
}

View File

@ -0,0 +1,8 @@
{
"AgileConfig": {
"appId": "KonSoft.Shared.DbMigrator",
"name": "KonSoft.Shared.DbMigrator",
"nodes": "https://config.konsoft.top/",
"secret": "DBE31703-14F9-4B01-893D-900B8380CE04"
}
}