Führen Sie eine Aktion aus, wenn alle registrierten Dienste in .NET Generic Host entsorgen werden
Posted: 06 May 2025, 10:35
Ich muss eine Aktion (d. H. E., Log -Erfolgsabschaltung) ausführen, wenn alle registrierten Dienste in .NET Generic Host entsorgt werden. Ich hoffe
Code: Select all
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading.Tasks;
namespace IHostCtrlC;
internal class Program
{
static async Task Main()
{
var hostBuilder = Host.CreateDefaultBuilder().ConfigureServices(services =>
{
services.AddSingleton();
});
var host = hostBuilder.Build();
host.Services.GetRequiredService().WriteText();
await host.RunAsync();
}
}
internal interface IWriteTextService : IDisposable
{
void WriteText();
}
internal class WriteTextService : IWriteTextService
{
public WriteTextService(IHostApplicationLifetime hostApplicationLifetime)
{
hostApplicationLifetime.ApplicationStopped.Register(() => Console.WriteLine("ApplicationStopped"));
}
public void WriteText() => Console.WriteLine("Sample text from GetTextService");
public void Dispose() => Console.WriteLine("GetTextService.Dispose()");
}