刘磊
2025-04-19 823752496e2a4cdb6a1fb36227cd15b8b7135336
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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 WIDESEA_Core.Helper;
using WIDESEA_Core.Seed;
 
namespace WIDESEA_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;
        }
 
    }
}