Home > Back-end >  How can I execute a method before Blazor Server shutdown?
How can I execute a method before Blazor Server shutdown?

Time:09-25

My program must execute a method called Checksum() before application shutdown because when the application run again must validate the checksum to continue. If the method doesn't run before the application shutdown, the changes on the database will not be noticed.

I tried with Circuit but that isn't what I need. It runs the method when a user closes the connection with the server but not when the server shuts down.

I tried with IHostApplicationLifetime but that also doesn't work. I also tried with IApplicationLifetime, and wasn't able to do what I wanted to.

I tried all these in the BlazorServer Program.cs and I put breakpoints.

I haven't found good information on it. Probably the way that I implemented the IApplicationLifetime or IHostApplicationLifetime was wrong.

CodePudding user response:

Just found the answer.

using Microsoft.Extensions.Hosting.IHostedService Program.cs:

public class Program: IHostedService
{
  public static void Main(string[] args)
  {
      CreateHostBuilder(args).Build().Run();
  }

  public static IHostBuilder CreateHostBuilder(string[] args) =>
      Host.CreateDefaultBuilder(args)
          .ConfigureWebHostDefaults(webBuilder =>
          {
              webBuilder.UseStartup<Startup>();
          });

  public async Task StartAsync(CancellationToken cancellationToken)
  {
      //RUN A METHOD ON APPLICATION START
  }

  public async Task StopAsync(CancellationToken cancellationToken)
  {
      //RUN A METHOD ON APPLICATION STOP
  }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddHostedService<Program>(); //ADD THIS
}

I found it here: LINK

  • Related