using System; using System.Threading; using System.Threading.Tasks; using EntrustSettle.Common; using EntrustSettle.Common.Seed; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace EntrustSettle.Extensions; public sealed class SeedDataHostedService : IHostedService { private readonly SeedContext _myContext; private readonly ILogger _logger; public SeedDataHostedService(SeedContext myContext, ILogger logger) { _myContext = myContext; _logger = logger; } public async Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("Start Initialization Db Seed Service!"); await DoWork(); } private async Task DoWork() { try { await Task.CompletedTask; // 初始化Main数据库结构 DBSeed.Seed(_myContext); // 初始化日志数据库结构 if (AppSettings.app("AppSettings", "LogToDb").ObjToBool()) { DBSeed.MigrationLogs(_myContext); } } catch (Exception ex) { _logger.LogError(ex, "Error occured seeding the Database."); throw; } } public Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("Stop Initialization Db Seed Service!"); return Task.CompletedTask; } }