gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:16:56 24 4
gpt4 key购买 nike

关注此 answer ,我想注入(inject)IHostApplicationLifetime在我的类里面正确关机时方法StartAsync结束了。

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

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();
}

谢谢 !

最佳答案

框架已经默认添加了它,因此您应该能够从托管服务作为注入(inject)依赖项访问它。
简化示例

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

关于c# - 如何在我的服务中获取 IHostApplicationLifetime 并将其注入(inject)容器(控制台应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59650230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com