using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Admin.NET.Plugin.AiDOP.DataPlatform.Schema; /// /// HTTP 已开始监听后再执行历史来源身份回填,避免数据迁移阻塞宿主启动。 /// public sealed class MdpSourceIdentityBackfillWorker : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private readonly IHostApplicationLifetime _lifetime; private readonly ILogger _logger; public MdpSourceIdentityBackfillWorker( IServiceScopeFactory scopeFactory, IHostApplicationLifetime lifetime, ILogger logger) { _scopeFactory = scopeFactory; _lifetime = lifetime; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); using var registration = _lifetime.ApplicationStarted.Register(() => started.TrySetResult()); try { await started.Task.WaitAsync(stoppingToken); } catch (OperationCanceledException) { return; } try { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); await MdpSchemaAligner.BackfillProvenSourceAsync(db); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { } catch (Exception ex) { _logger.LogWarning(ex, "中台历史来源身份回填失败;不影响 HTTP 服务"); } } }