0
votes

I am building a Blazor app (both wasm and server) which both share an API and a set of Services. I have the services broken out into its own class library. There are probably 50 or so services and I dont want to duplicate the service declarations in the Server and WASM configuration sections.

Current Situation

WASM

public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");

            var zooAPI = new Uri("http://localhost:51552/api/v1/");

            builder.Services.AddHttpClient<IZooService, ZooService>(client => client.BaseAddress = zooAPI);

        await builder.Build().RunAsync();
    }

Server

public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();

            var zooAPI = new Uri("http://localhost:51552/api/v1/");

            services.AddHttpClient<IZooService, ZooService>(client => client.BaseAddress = zooAPI);
        }

Since both of these register the services which will end up being over 50 services id like to add a Startup within my Services Class Library.

[assembly: HostingStartup(typeof(Zoo.Services.ServicesStartup))]
namespace Zoo.Services
{
    public class ServicesStartup : IHostingStartup
    {
        public void Configure(IWebHostBuilder builder)
        {
            var zooAPI = new Uri("http://localhost:51552/api/v1/");

            builder.ConfigureServices((context, services) =>
            {
                services.AddHttpClient<IZooService, ZooService>(client => client.BaseAddress = zooAPI);
            });
        }

    }
}

The issue I have is that this Startup is not being recognized and the Services are not being registered. The exception is "An Unhandled exception occured while processing the request. InvalidOperationException: Cannot provide a value for property 'ZooService'. There is no registered service of type IZooService.

What am I missing to have this ServiceStartup recognized and the registered upon app start?

1

1 Answers

-1
votes

In order for the Blazor app to know there is a HostingStartup it needs to read you need to tell it the assemblies to look into.

For Server Hosting in the Program.cs you can add the StartupAssemblies Keys or you can add it to the enviornmentvariables ASPNETCORE_HOSTINGSTARTUPASSEMBLIES

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseSetting(WebHostDefaults.HostingStartupAssembliesKey, "Zoo.Services").UseStartup<Startup>();
                });

I have not figured out how to add it to the WASM yet