作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
关注此 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/
我是一名优秀的程序员,十分优秀!