host service

    public class DemoService01
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }

    // 由于Host service是单例的,所以无法使用IOC注入非单例服务
    // 需要使用IServiceScopeFactory来生成scope,然后调用服务
    public class HostService01 : BackgroundService
    {
        private IServiceScope Scope { get; init; }
        public HostService01(IServiceScopeFactory factory)
        {
            Scope = factory.CreateScope();
        }

        // ???? 没看到这个Dispose()被调用
        public override void Dispose()
        {
            Console.WriteLine("dispose scope");
            Scope.Dispose();

            base.Dispose();
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Console.WriteLine("HostService01 started.");
            await Task.Delay(5000);

            Console.WriteLine("hello world!!!");

            // 通过Scope获取service
            DemoService01 service = Scope.ServiceProvider.GetRequiredService<DemoService01>();
            Console.WriteLine(service.Add(1, 2));

            await Task.Delay(5000);

            Console.WriteLine("HostService01 stopped.");
        }
    }

注册service

builder.Services.AddTransient<DemoService01>();
builder.Services.AddHostedService<HostService01>();

注意: 如果Host service中抛出异常,那么整个应用就会终止