Blazor Modular UI application hosted in service container, routing problem

Viewed 38

I'm trying to create a Blazor application where ultimately the host and layout are declared in one Razor Class Library or application and applied across other RCL modules. I've tried a few variants but haven't been able to get the effect I wanted due to routing. I THINK, what I need to know is how to map a fallback route to the host page when the Blazor application itself is run as a HostedService in another process.

As an example, If I create an application using the standard, included "Blazor Server Application" template and move the application builder logic into a service as below:

Solution Structure

The contents of this "UiHostService" being as follows:

using Alpha.ReferenceApp.Data;

namespace Alpha.ReferenceApp.Services
{
public class UiHostService : IHostedService
{
    WebApplication? _app;

    public Task StartAsync(CancellationToken cancellationToken)
    {
        var builder = WebApplication.CreateBuilder(Environment.GetCommandLineArgs());

        // Add services to the container.
        builder.Services.AddRazorPages();
        builder.Services.AddServerSideBlazor();
        builder.Services.AddSingleton<WeatherForecastService>();

        _app = builder.Build();

        // Configure the HTTP request pipeline.
        if (!_app.Environment.IsDevelopment())
        {
            _app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            _app.UseHsts();
        }

        _app.UseHttpsRedirection();
        _app.UseStaticFiles();
        _app.UseRouting();
        _app.MapBlazorHub();
        _app.MapFallbackToPage("/_Host");

        return _app.StartAsync(cancellationToken);
    }

    public Task StopAsync(CancellationToken cancellationToken) =>
        _app?.StopAsync(cancellationToken) ?? Task.CompletedTask;
}

}

And the program's SVM being simply:

public static async Task Main() => await Host.CreateDefaultBuilder()
        .ConfigureServices(svc => svc
            .AddHostedService<UiHostService>()
        )
        .Build()
        .RunAsync();

This seems to work, and I believe I would be able to load areas/pages from an RCL. However, loading this in a service container in a separate application doesn't work (ie: in the "Alpha.HostProcess" program.cs):

using Alpha.ReferenceApp.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

await Host.CreateDefaultBuilder().ConfigureServices(svc => svc
    .AddHostedService<UiHostService>()
)
.Build()
.RunAsync();

It can't map the route back to the fallback "_Host" page. I'm a little new to Blazor so can anyone tell me why this is or set this up correctly? I've tried this a few different ways using Areas/Pages etc. but I'm still missing something.

0 Answers
Related