using Connected.Middleware; using Connected.Startup; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Microsoft.Extensions.DependencyInjection; namespace Connected; public static class Instance { public static WebAssemblyHost Host { get; private set; } = default!; private static IServiceProvider ServiceProvider { get; set; } = default!; internal static T? GetService() { return ServiceProvider.GetService(); } public static async Task Start(List startups, Dictionary args) where TApp : IComponent { var builder = WebAssemblyHostBuilder.CreateDefault(UnpackArguments(args)); builder.RootComponents.Add("#app"); builder.RootComponents.Add("head::after"); builder.Services.AddHttpClient(); builder.Services.AddSingleton(typeof(IComponentMiddlewareService), typeof(ComponentMiddlewareService)); builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); foreach (var startup in startups) await startup.ConfigureServices(builder.Services); Host = builder.Build(); foreach (var startup in startups) await startup.Configure(Host); await Host.RunAsync(); } private static string[] UnpackArguments(Dictionary args) { var result = new string[args.Count]; for (var i = 0; i < args.Count; i++) { var arg = args.ElementAt(i); result[i] = string.IsNullOrWhiteSpace(arg.Value) ? arg.Key : $"{arg.Key}={arg.Value}"; } return result; } public static void UseMiddlewareComponent(this WebAssemblyHost app) { if (app.Services.GetService() is not IComponentMiddlewareService service) throw new NullReferenceException(nameof(IComponentMiddlewareService)); service.Add(); } }