.net core 中使用HostService

HostService可以用来初始化数据

  1. 新建一个类继承自BackgroundService
    注意hostservice中服务注入的方式
namespace EFCoreJWT
{
    public class HostServiceDemo : BackgroundService
    {
        private readonly IServiceScopeFactory _scopeFactory;
        private readonly IServiceScope _serviceScope;

        public HostServiceDemo(IServiceScopeFactory scopeFactory)
        {
            _scopeFactory = scopeFactory;
            //通过这个注入DBContext
            _serviceScope = _scopeFactory.CreateScope();
        }


        public override void Dispose()
        {
            base.Dispose();
            _serviceScope.Dispose();
        }

        protected async override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Console.WriteLine("start");

            MyDbContext myDbContext = _serviceScope.ServiceProvider.GetService<MyDbContext>();

            await Task.Delay(10);
            Console.WriteLine("end");

        }
    }
}

  1. programes注入
builder.Services.AddHostedService<HostServiceDemo>();

你可能感兴趣的:(.netCore,.netcore,c#)