StartAsync not triggered when RunAsync is called from Console Application

I’m trying to use dependency injection from a .NET 6 console application.

I’ve got a class called Startup which inherits from IHostedService and it has both the StartupAsync and StopAsync functions defined:

public async Task StartAsync(CancellationToken cancellationToken)
{
    Console.WriteLine("Host started!");
    return Task.CompletedTask;
}

public Task StopAsync(CancellationToken cancellationToken)
{
    Console.WriteLine("Host stopped!");
    return Task.CompletedTask;
}

And from my Program.cs, I’ve got the following code defined:

var host = Host.CreateDefaultBuilder(args)
             .ConfigureServices((hostContext, services) =>
             {
               services.AddInfrastructure(Configuration.Load());
               services.BuildServiceProvider().MigrateDatabase<ApplicationDbContext>();
               services.AddSingleton<Startup>();
             })
             .UseConsoleLifetime()
             .Build();

 await host.RunAsync();

Any why the StartupAsync is not being triggered when it is supposed to when the RunAsynch() is called?

>Solution :

I believe you are adding the startup class erroneously. Instead of

services.AddSingleton<Startup>();

try

services.AddHostedService<Startup>();

Leave a Reply