如何在我的服务中获取 IHostApplicationLifetime 并将其注入容器(控制台应用程序)

How to get and inject the IHostApplicationLifetime in my service to the container (Console App)

在此 之后,我想在 class 中注入 IHostApplicationLifetime 以在方法 StartAsync 结束时正常关闭。

但我不知道如何从控制台获取 applicationLifetime 并通过内置的 dotnet 核心 IoC 容器注入它:

public static IHostBuilder CreateHostBuilder(string[] args)
{
    return Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.SetBasePath(Directory.GetCurrentDirectory())
            .AddCommandLine(args)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
        })
        .ConfigureServices((hostContext, services) =>
        {
            services.Configure<ConnectionStringConfiguration>(hostContext.Configuration.GetSection("ConnectionStrings"));
            services.AddTransient<ISmtpClient, MySmtpClient>();
            services.AddTransient<IEmailService, EmailService>();
            services.AddSingleton<IHostApplicationLifetime>(????); // What should I put here ????
            services.AddHostedService<EInvoiceSenderService>();
        })
        .UseSerilog();
}

谢谢!

它已经被框架默认添加,因此您应该能够从托管服务中将其作为注入的依赖项进行访问。

简化示例

public class EInvoiceSenderService: IHostedService {
    private readonly ILogger logger;
    private readonly IHostApplicationLifetime appLifetime;

    public EInvoiceSenderService(
        ILogger<LifetimeEventsHostedService> logger, 
        IHostApplicationLifetime appLifetime) { //<--- INJECTED DEPENDENCY
        this.logger = logger;
        this.appLifetime = appLifetime;
    }

    public Task StartAsync(CancellationToken cancellationToken) {
        appLifetime.ApplicationStarted.Register(OnStarted);
        appLifetime.ApplicationStopping.Register(OnStopping);
        appLifetime.ApplicationStopped.Register(OnStopped);

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken) {
        return Task.CompletedTask;
    }


    private void OnStarted() {
        logger.LogInformation("OnStarted has been called.");

        // Perform post-startup activities here
    }

    private void OnStopping() {
        logger.LogInformation("OnStopping has been called.");

        // Perform on-stopping activities here
    }

    private void OnStopped() {
        logger.LogInformation("OnStopped has been called.");

        // Perform post-stopped activities here
    }    
}

参考:.NET Generic Host: IHostApplicationLifetime