Home > Mobile >  StartAsync not triggered when RunAsync is called from Console Application
StartAsync not triggered when RunAsync is called from Console Application

Time:01-25

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?

CodePudding user response:

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

services.AddSingleton<Startup>();

try

services.AddHostedService<Startup>();
  • Related