Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading