dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.5k stars 10.04k forks source link

Add hosted service feature for `WebAssemblyHost` #33537

Closed WeihanLi closed 3 years ago

WeihanLi commented 3 years ago

Is your feature request related to a problem? Please describe.

I wanna schedule a background service when the Blazor Wasm App loaded, but now the WebAssemblyHost does not support IHostedService, so I'm wondering that if we could add HostedService support for Blazor Wasm App.

Describe the solution you'd like

Start the hosted services in WebAssemblyHost.RunAsync method

Additional context

It may increase the Blazor app size

mkArtakMSFT commented 3 years ago

Thanks for contacting us. Can you please share more details about why it's important for you to have support for HostedServices in Blazor WebAssembly apps? Have you considered other options and what were these?

WeihanLi commented 3 years ago

I wanna run a background scheduler when the app starts. Currently, I just implement a simple background service and start the background service before the host starts

var host = builder.Build();
await host.Services.GetRequiredService<TodoScheduler>().Start();
await host.RunAsync();

Background service implement:

public Task Start()
{
    var task = Execute();
    if (task.IsCompleted)
    {
        return task;
    }
    return Task.CompletedTask;
}

private async Task Execute(){}

For more details, there's a simple sample: https://github.com/WeihanLi/SparkTodo/blob/master/SparkTodo.WebExtension/Program.cs

mkArtakMSFT commented 3 years ago

Thanks for the additional details. Your solution looks good and we don't have any plans to implement special feature for this in the near future.