using Microsoft.AspNetCore.Hosting; 
 | 
using Microsoft.Extensions.DependencyInjection; 
 | 
using Microsoft.Extensions.Hosting; 
 | 
using Microsoft.Extensions.Logging; 
 | 
using System; 
 | 
using System.Collections.Generic; 
 | 
using System.Linq; 
 | 
using System.Text; 
 | 
using System.Threading.Tasks; 
 | 
using WIDESEAWCS_Core.Helper; 
 | 
using WIDESEAWCS_Core.Seed; 
 | 
  
 | 
namespace WIDESEAWCS_Core 
 | 
{ 
 | 
    public sealed class SeedDataHostedService : IHostedService 
 | 
    { 
 | 
        private readonly DBContext _dbContext; 
 | 
        private readonly ILogger<SeedDataHostedService> _logger; 
 | 
        private readonly string _webRootPath; 
 | 
        private readonly IServiceProvider _serviceProvider; 
 | 
  
 | 
        public SeedDataHostedService( 
 | 
            IServiceProvider serviceProvider, 
 | 
            IWebHostEnvironment webHostEnvironment, 
 | 
            ILogger<SeedDataHostedService> logger) 
 | 
        { 
 | 
            _serviceProvider = serviceProvider; 
 | 
            _logger = logger; 
 | 
            _webRootPath = webHostEnvironment.WebRootPath; 
 | 
  
 | 
            using var scope = _serviceProvider.CreateScope(); 
 | 
  
 | 
            var dbContext = scope.ServiceProvider.GetService<DBContext>(); 
 | 
            //dbContext.Db.Aop.DataExecuting = SqlSugarAop.DataExecuting; 
 | 
            _dbContext = dbContext; 
 | 
        } 
 | 
  
 | 
        public async Task StartAsync(CancellationToken cancellationToken) 
 | 
        { 
 | 
            _logger.LogInformation("Start Initialization Db Seed Service!"); 
 | 
            await DoWork(); 
 | 
        } 
 | 
  
 | 
        private async Task DoWork() 
 | 
        { 
 | 
            try 
 | 
            { 
 | 
                //if (AppSettings.app("AppSettings", "SeedDBEnabled").ObjToBool() || AppSettings.app("AppSettings", "SeedDBDataEnabled").ObjToBool()) 
 | 
                { 
 | 
                    // 使用 myScopedService 执行任务 
 | 
  
 | 
                    await DBSeed.SeedAsync(_dbContext, _webRootPath); 
 | 
  
 | 
                    //多租户 同步 
 | 
                    //await DBSeed.TenantSeedAsync(_dbContext); 
 | 
                } 
 | 
            } 
 | 
            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; 
 | 
        } 
 | 
  
 | 
    } 
 | 
} 
 |