You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Connected.Components/Instance.cs

64 lines
1.9 KiB

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<T>()
{
return ServiceProvider.GetService<T>();
}
public static async Task Start<TApp>(List<IStartup> startups, Dictionary<string, string> args) where TApp : IComponent
{
var builder = WebAssemblyHostBuilder.CreateDefault(UnpackArguments(args));
builder.RootComponents.Add<TApp>("#app");
builder.RootComponents.Add<HeadOutlet>("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<string, string> 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<TMiddleware, TComponent>(this WebAssemblyHost app)
{
if (app.Services.GetService<IComponentMiddlewareService>() is not IComponentMiddlewareService service)
throw new NullReferenceException(nameof(IComponentMiddlewareService));
service.Add<TMiddleware, TComponent>();
}
}