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

C# 如何获取我的服务中的IHostApplicationLifetime并将其注入容器(控制台应用程序),c#,.net-core,dependency-injection,console-application,ioc-container,C#,.net Core,Dependency Injection,Console Application,Ioc Container,接下来,我想在类中注入IHostApplicationLifetime,以便在方法StartAsync结束时正确关闭 但我不知道如何从控制台获取applicationLifetime,并通过内置的dotnet core IoC容器注入它: public static IHostBuilder CreateHostBuilder(string[] args) { return Host.CreateDefaultBuilder(args) .ConfigureAppConf

接下来,我想在类中注入
IHostApplicationLifetime
,以便在方法
StartAsync
结束时正确关闭

但我不知道如何从控制台获取applicationLifetime,并通过内置的dotnet core 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();
}
公共静态IHostBuilder CreateHostBuilder(字符串[]args)
{
返回Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext,config)=>
{
config.SetBasePath(Directory.GetCurrentDirectory())
.AddCommandLine(args)
.AddJsonFile(“appsettings.json”,可选:false,reloadOnChange:true);
})
.ConfigureServices((主机上下文,服务)=>
{
Configure(hostContext.Configuration.GetSection(“ConnectionString”);
services.AddTransient();
services.AddTransient();
services.AddSingleton(??)//我应该在这里放什么????
services.AddHostedService();
})
.useserlog();
}

谢谢大家!

框架默认情况下已经添加了它,因此您应该能够从托管服务访问它

简化示例

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

    public EInvoiceSenderService(
        ILogger<LifetimeEventsHostedService> logger, 
        IHostApplicationLifetime appLifetime) {
        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
    }    
}
公共类EInvoiceSenderService:IHostedService{
专用只读ILogger记录器;
私有只读IHostApplicationLifetime ApplyTime;
公共EInvoiceSenderService(
ILogger记录器,
iHostApplication生命周期(生命周期){
this.logger=记录器;
this.appLifetime=appLifetime;
}
公共任务StartSync(CancellationToken CancellationToken){
appLifetime.ApplicationStarted.Register(OnStarted);
appLifetime.ApplicationStopping.Register(OnStopping);
appLifetime.ApplicationStopped.Register(OnStopped);
返回Task.CompletedTask;
}
公共任务StopAsync(CancellationToken CancellationToken){
返回Task.CompletedTask;
}
私有void OnStarted(){
logger.LogInformation(“已调用OnStarted”);
//在此处执行启动后活动
}
私有void OnStopping(){
logger.LogInformation(“已调用OnStopping”);
//在此处执行停止活动
}
私有空间{
logger.LogInformation(“已调用OnStock”);
//在此处执行停止后的活动
}    
}

参考资料

谢谢!!如果没有您的回答,我将再次搜索&再次搜索……尽管文档中也有相同的说明,但您似乎无法注册返回“void”的方法。它必须返回一个Acion。也许有什么变化,文档没有更新?Idk。