From 4ca0a748802d71995e42252534ca0bc2df84133f Mon Sep 17 00:00:00 2001 From: Tewr Date: Sun, 7 Jan 2024 15:26:18 +0100 Subject: [PATCH] Feature/v4 stabilisation (#93) * IJSRuntime Extension functional * Removed useless dotnet config. Added configurable tracing output * Remove commented code from ServiceCollectionHelper example * Cleanup warning exceptions --- .../BlazorWorker.Demo.IoCExample.csproj | 19 ++- .../MyIndexDBService.cs | 66 --------- .../MyIndexDBServiceStartup.cs | 36 ----- .../MyIocService.cs | 3 +- .../MyServiceStartup.cs | 6 +- .../ServiceCollectionHelper.cs | 6 +- .../SetupIndexedDBExtensions.cs | 37 ------ .../BlazorWorker.Demo.Client.csproj | 4 +- .../Pages/IndexedDB.razor | 2 - .../Shared/NavMenu.razor | 2 +- .../Pages/IndexedDB.razor | 2 - .../Shared/NavMenu.razor | 2 +- .../Shared/BlazorWorker.Demo.Shared.csproj | 4 + .../BlazorWorker.Demo.SharedPages.csproj | 3 +- .../SharedPages/Pages/CoreExample.razor | 4 +- .../SharedPages/Pages/Http.razor | 4 +- .../SharedPages/Pages/IoCExamplePage.razor | 125 ++++++++++++++++++ .../BlazorWorker.Core.xml | 8 -- .../BlazorWorker.Extensions.JSRuntime.csproj | 49 ++++--- .../BlazorWorker.Extensions.JSRuntime.xml | 84 ++++++++++++ .../BlazorWorkerJSRuntime.cs | 75 ++++++++--- .../BlazorWorkerJsRuntimeSetupExtensions.cs | 27 ++-- .../DefaultBlazorWorkerJSRuntimeSerializer.cs | 12 +- .../DotNetObjectReferenceTracker.cs | 8 +- .../JSInvokeService.cs | 61 +++++++++ .../wwwroot/BlazorWorkerJSRuntime.js | 43 +++++- ...azorWorker.BackgroundServiceFactory.csproj | 4 + .../WorkerBackgroundServiceExtensions.cs | 8 +- .../WorkerBackgroundServiceProxy.cs | 4 - ...lazorWorker.WorkerBackgroundService.csproj | 4 + .../InitWorkerInstanceException.cs | 25 ---- .../WorkerInstanceManager.cs | 7 +- .../BlazorWorker.WorkerCore.csproj | 4 + .../BlazorWorker.WorkerCore.xml | 6 - .../JSInvokeException.cs | 21 --- .../JSInvokeService.cs | 25 ---- .../SimpleInstanceService.cs | 2 + .../WorkerException.cs | 21 --- src/BlazorWorker/BlazorWorker.Core.csproj | 4 + src/BlazorWorker/BlazorWorker.js | 38 ++++-- .../CoreInstanceService.cs | 6 - .../SimpleInstanceServiceProxy.cs | 8 +- 42 files changed, 492 insertions(+), 387 deletions(-) delete mode 100644 src/BlazorWorker.Demo.IoCExample/MyIndexDBService.cs delete mode 100644 src/BlazorWorker.Demo.IoCExample/MyIndexDBServiceStartup.cs delete mode 100644 src/BlazorWorker.Demo.IoCExample/SetupIndexedDBExtensions.cs delete mode 100644 src/BlazorWorker.Demo/Net7/Client/BlazorWorker.Demo.Client/Pages/IndexedDB.razor delete mode 100644 src/BlazorWorker.Demo/Net8/Client/BlazorWorker.Demo.Client/Pages/IndexedDB.razor create mode 100644 src/BlazorWorker.Demo/SharedPages/Pages/IoCExamplePage.razor delete mode 100644 src/BlazorWorker.Extensions.JSRuntime/BlazorWorker.Core.xml create mode 100644 src/BlazorWorker.Extensions.JSRuntime/BlazorWorker.Extensions.JSRuntime.xml create mode 100644 src/BlazorWorker.Extensions.JSRuntime/JSInvokeService.cs delete mode 100644 src/BlazorWorker.WorkerBackgroundService/InitWorkerInstanceException.cs delete mode 100644 src/BlazorWorker.WorkerCore/JSInvokeException.cs delete mode 100644 src/BlazorWorker.WorkerCore/JSInvokeService.cs delete mode 100644 src/BlazorWorker.WorkerCore/WorkerException.cs diff --git a/src/BlazorWorker.Demo.IoCExample/BlazorWorker.Demo.IoCExample.csproj b/src/BlazorWorker.Demo.IoCExample/BlazorWorker.Demo.IoCExample.csproj index 13697a1..a0defea 100644 --- a/src/BlazorWorker.Demo.IoCExample/BlazorWorker.Demo.IoCExample.csproj +++ b/src/BlazorWorker.Demo.IoCExample/BlazorWorker.Demo.IoCExample.csproj @@ -5,18 +5,23 @@ Debug;Release;Nuget + + 1701;1702;1591;CA1416 + + - + + - - + + + - - - + + + - diff --git a/src/BlazorWorker.Demo.IoCExample/MyIndexDBService.cs b/src/BlazorWorker.Demo.IoCExample/MyIndexDBService.cs deleted file mode 100644 index 52de92b..0000000 --- a/src/BlazorWorker.Demo.IoCExample/MyIndexDBService.cs +++ /dev/null @@ -1,66 +0,0 @@ -using Microsoft.JSInterop; -using System; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; -using TG.Blazor.IndexedDB; - -namespace BlazorWorker.Demo.IoCExample -{ - public class MyIndexDBService - { - private readonly IJSRuntime jsRuntime; - private readonly IndexedDBManager indexedDBManager; - private bool isIndexDBManagerInitialized; - - public MyIndexDBService( - IJSRuntime jsRuntime, - IndexedDBManager indexDBManager) - { - //Console.WriteLine($"{nameof(MyIndexDBService)} instance created"); - this.jsRuntime = jsRuntime; - this.indexedDBManager = indexDBManager; - } - - public async Task GetPersonName(long id) - { - try - { - //Console.WriteLine($"{nameof(GetPersonName)}({id}) called."); - await EnsureInitializedAsync(); - //Console.WriteLine($"{nameof(GetPersonName)}({id}): Get Store name..."); - var storeName = indexedDBManager.Stores[0].Name; - //output += $"{rn}{LogDate()} retrieving test person..."; - //Console.WriteLine($"{nameof(GetPersonName)}({id}): GetRecords from store '{storeName}'"); - var testPersons = (await this.indexedDBManager.GetRecords(storeName)); - foreach (var item in testPersons) - { - if (item.Id == id) - { - return item.Name ?? "[empty name]"; - } - } - - return "N/A"; - - } - catch (System.Exception e) - { - Console.WriteLine($"{nameof(GetPersonName)} :{e})"); - throw; - } - } - - private async Task EnsureInitializedAsync() - { - if (!isIndexDBManagerInitialized) - { - // The following is a workaround as indexedDb.Blazor.js explicitly references "window" - await this.jsRuntime.InvokeVoidAsync("eval", "(() => { self.window = self; return null; })()"); - await this.jsRuntime.InvokeVoidAsync("importLocalScripts", "_content/TG.Blazor.IndexedDB/indexedDb.Blazor.js"); - - isIndexDBManagerInitialized = true; - } - } - - } -} diff --git a/src/BlazorWorker.Demo.IoCExample/MyIndexDBServiceStartup.cs b/src/BlazorWorker.Demo.IoCExample/MyIndexDBServiceStartup.cs deleted file mode 100644 index 28f7fe3..0000000 --- a/src/BlazorWorker.Demo.IoCExample/MyIndexDBServiceStartup.cs +++ /dev/null @@ -1,36 +0,0 @@ -using BlazorWorker.Extensions.JSRuntime; -using BlazorWorker.WorkerCore; -using Microsoft.Extensions.DependencyInjection; -using System; - -namespace BlazorWorker.Demo.IoCExample -{ - public class MyIndexDBServiceStartup - { - private readonly IServiceProvider serviceProvider; - private readonly IWorkerMessageService workerMessageService; - - /// - /// The constructor uses the built-in injection for library-native services such as the . - /// - /// - public MyIndexDBServiceStartup(IWorkerMessageService workerMessageService) - { - this.workerMessageService = workerMessageService; - serviceProvider = ServiceCollectionHelper.BuildServiceProviderFromMethod(Configure); - } - - public T Resolve()=> serviceProvider.GetService(); - - public void Configure(IServiceCollection services) - { - services.AddTransient() - .AddBlazorWorkerJsRuntime() - .AddSingleton() - .AddSingleton(workerMessageService) - .AddIndexedDbDemoPersonConfig(); - } - } - - -} diff --git a/src/BlazorWorker.Demo.IoCExample/MyIocService.cs b/src/BlazorWorker.Demo.IoCExample/MyIocService.cs index 60aa4d1..02cfca3 100644 --- a/src/BlazorWorker.Demo.IoCExample/MyIocService.cs +++ b/src/BlazorWorker.Demo.IoCExample/MyIocService.cs @@ -2,7 +2,6 @@ using Microsoft.JSInterop; using System; using System.Threading.Tasks; -using TG.Blazor.IndexedDB; namespace BlazorWorker.Demo.IoCExample { @@ -26,10 +25,10 @@ public MyIocService( public async Task Five() { - await this.WorkerMessageService.PostMessageAsync($"aaaaaaa"); this.FiveCalled?.Invoke(this, FiveCalledCounter++); try { + Console.WriteLine($"MyIocService: Attempting JsRuntime InvokeAsync..."); var theNumberOfTheBeast = await this.JSRuntime.InvokeAsync("eval", "(function(){ console.log('Hello world invoke call from MyIocService'); return 666; })()"); diff --git a/src/BlazorWorker.Demo.IoCExample/MyServiceStartup.cs b/src/BlazorWorker.Demo.IoCExample/MyServiceStartup.cs index cfe8ec9..0ebcc39 100644 --- a/src/BlazorWorker.Demo.IoCExample/MyServiceStartup.cs +++ b/src/BlazorWorker.Demo.IoCExample/MyServiceStartup.cs @@ -1,8 +1,10 @@ -using BlazorWorker.Extensions.JSRuntime; -using BlazorWorker.WorkerCore; +using BlazorWorker.WorkerCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.JSInterop; using System; +using BlazorWorker.Extensions.JSRuntime; + namespace BlazorWorker.Demo.IoCExample { public class MyServiceStartup diff --git a/src/BlazorWorker.Demo.IoCExample/ServiceCollectionHelper.cs b/src/BlazorWorker.Demo.IoCExample/ServiceCollectionHelper.cs index e2616f0..59e1963 100644 --- a/src/BlazorWorker.Demo.IoCExample/ServiceCollectionHelper.cs +++ b/src/BlazorWorker.Demo.IoCExample/ServiceCollectionHelper.cs @@ -1,5 +1,9 @@ using Microsoft.Extensions.DependencyInjection; +using Microsoft.JSInterop; using System; +using System.Diagnostics; +using System.Linq; +using System.Reflection; namespace BlazorWorker.Demo.IoCExample { @@ -11,7 +15,7 @@ public static IServiceProvider BuildServiceProviderFromMethod(Configure configur { var serviceCollection = new ServiceCollection(); configureMethod(serviceCollection); - return serviceCollection.BuildServiceProvider(); + return serviceCollection.BuildServiceProvider(); } } } diff --git a/src/BlazorWorker.Demo.IoCExample/SetupIndexedDBExtensions.cs b/src/BlazorWorker.Demo.IoCExample/SetupIndexedDBExtensions.cs deleted file mode 100644 index 84eca6a..0000000 --- a/src/BlazorWorker.Demo.IoCExample/SetupIndexedDBExtensions.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using System.Collections.Generic; -using TG.Blazor.IndexedDB; - -namespace BlazorWorker.Demo.IoCExample -{ - public static class SetupIndexedDBExtensions - { - public static IServiceCollection AddIndexedDbDemoPersonConfig(this IServiceCollection services) - { - services.AddIndexedDB(dbStore => - { - dbStore.DbName = "TheFactory"; //example name - dbStore.Version = 1; - - dbStore.Stores.Add(new StoreSchema - { - Name = "TestPersons", - PrimaryKey = new IndexSpec { Name = "id", KeyPath = "id", Auto = true }, - Indexes = new List - { - new IndexSpec{ Name = "name", KeyPath = "name", Auto = false }, - } - }); - }); - - return services; - } - } - - public class Person - { - public long? Id { get; set; } - public string Name { get; set; } - - } -} diff --git a/src/BlazorWorker.Demo/Net7/Client/BlazorWorker.Demo.Client/BlazorWorker.Demo.Client.csproj b/src/BlazorWorker.Demo/Net7/Client/BlazorWorker.Demo.Client/BlazorWorker.Demo.Client.csproj index 188fd08..8389f91 100644 --- a/src/BlazorWorker.Demo/Net7/Client/BlazorWorker.Demo.Client/BlazorWorker.Demo.Client.csproj +++ b/src/BlazorWorker.Demo/Net7/Client/BlazorWorker.Demo.Client/BlazorWorker.Demo.Client.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/src/BlazorWorker.Demo/Net7/Client/BlazorWorker.Demo.Client/Pages/IndexedDB.razor b/src/BlazorWorker.Demo/Net7/Client/BlazorWorker.Demo.Client/Pages/IndexedDB.razor deleted file mode 100644 index 34bff58..0000000 --- a/src/BlazorWorker.Demo/Net7/Client/BlazorWorker.Demo.Client/Pages/IndexedDB.razor +++ /dev/null @@ -1,2 +0,0 @@ -@page "/IndexedDB" - \ No newline at end of file diff --git a/src/BlazorWorker.Demo/Net7/Client/BlazorWorker.Demo.Client/Shared/NavMenu.razor b/src/BlazorWorker.Demo/Net7/Client/BlazorWorker.Demo.Client/Shared/NavMenu.razor index 1c2d379..1e25fc7 100644 --- a/src/BlazorWorker.Demo/Net7/Client/BlazorWorker.Demo.Client/Shared/NavMenu.razor +++ b/src/BlazorWorker.Demo/Net7/Client/BlazorWorker.Demo.Client/Shared/NavMenu.razor @@ -20,7 +20,7 @@ @code { private bool collapseNavMenu = true; - private string NavMenuCssClass => collapseNavMenu ? "collapse" : null; + private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null; private void ToggleNavMenu() { diff --git a/src/BlazorWorker.Demo/Net8/Client/BlazorWorker.Demo.Client/Pages/IndexedDB.razor b/src/BlazorWorker.Demo/Net8/Client/BlazorWorker.Demo.Client/Pages/IndexedDB.razor deleted file mode 100644 index 34bff58..0000000 --- a/src/BlazorWorker.Demo/Net8/Client/BlazorWorker.Demo.Client/Pages/IndexedDB.razor +++ /dev/null @@ -1,2 +0,0 @@ -@page "/IndexedDB" - \ No newline at end of file diff --git a/src/BlazorWorker.Demo/Net8/Client/BlazorWorker.Demo.Client/Shared/NavMenu.razor b/src/BlazorWorker.Demo/Net8/Client/BlazorWorker.Demo.Client/Shared/NavMenu.razor index 1c2d379..1e25fc7 100644 --- a/src/BlazorWorker.Demo/Net8/Client/BlazorWorker.Demo.Client/Shared/NavMenu.razor +++ b/src/BlazorWorker.Demo/Net8/Client/BlazorWorker.Demo.Client/Shared/NavMenu.razor @@ -20,7 +20,7 @@ @code { private bool collapseNavMenu = true; - private string NavMenuCssClass => collapseNavMenu ? "collapse" : null; + private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null; private void ToggleNavMenu() { diff --git a/src/BlazorWorker.Demo/Shared/BlazorWorker.Demo.Shared.csproj b/src/BlazorWorker.Demo/Shared/BlazorWorker.Demo.Shared.csproj index dc669f5..5266957 100644 --- a/src/BlazorWorker.Demo/Shared/BlazorWorker.Demo.Shared.csproj +++ b/src/BlazorWorker.Demo/Shared/BlazorWorker.Demo.Shared.csproj @@ -5,6 +5,10 @@ Debug;Release;Nuget + + 1701;1702;1591;CA1416 + + diff --git a/src/BlazorWorker.Demo/SharedPages/BlazorWorker.Demo.SharedPages.csproj b/src/BlazorWorker.Demo/SharedPages/BlazorWorker.Demo.SharedPages.csproj index 054d9e5..42a06d4 100644 --- a/src/BlazorWorker.Demo/SharedPages/BlazorWorker.Demo.SharedPages.csproj +++ b/src/BlazorWorker.Demo/SharedPages/BlazorWorker.Demo.SharedPages.csproj @@ -6,7 +6,7 @@ - + @@ -19,6 +19,7 @@ + diff --git a/src/BlazorWorker.Demo/SharedPages/Pages/CoreExample.razor b/src/BlazorWorker.Demo/SharedPages/Pages/CoreExample.razor index bd14ff5..5c56069 100644 --- a/src/BlazorWorker.Demo/SharedPages/Pages/CoreExample.razor +++ b/src/BlazorWorker.Demo/SharedPages/Pages/CoreExample.razor @@ -65,12 +65,12 @@ backgroundService = worker.CreateCoreInstanceService(); - handle = await backgroundService.CreateInstance(options => + handle = await backgroundService.CreateInstance(/*options => options.AddConventionalAssemblyOfService() #if NET5_0_OR_GREATER .AddAssemblies("System.Text.RegularExpressions.dll") #endif - ); + */); output += $"{rn}{LogDate()} Background service created."; StateHasChanged(); diff --git a/src/BlazorWorker.Demo/SharedPages/Pages/Http.razor b/src/BlazorWorker.Demo/SharedPages/Pages/Http.razor index c23d894..0665cb3 100644 --- a/src/BlazorWorker.Demo/SharedPages/Pages/Http.razor +++ b/src/BlazorWorker.Demo/SharedPages/Pages/Http.razor @@ -51,9 +51,9 @@ sw.Start(); backgroundService = await worker.CreateBackgroundServiceAsync( - options => options + /*options => options .AddConventionalAssemblyOfService() - .AddHttpClient() + .AddHttpClient()*/ ); sw.Stop(); diff --git a/src/BlazorWorker.Demo/SharedPages/Pages/IoCExamplePage.razor b/src/BlazorWorker.Demo/SharedPages/Pages/IoCExamplePage.razor new file mode 100644 index 0000000..d8fe57f --- /dev/null +++ b/src/BlazorWorker.Demo/SharedPages/Pages/IoCExamplePage.razor @@ -0,0 +1,125 @@ +@using BlazorWorker.Demo.IoCExample +@inject IWorkerFactory workerFactory + +
+
+

.NET Worker Thread Service with IoC

+ + This page demonstrates IoC / dependency injection. + In this example, the class MyServiceStartup is a factory class for MyIocService. + The factory is implemented using ServiceCollection as an IoC Container. + + The factory also uses the extensions methods from BlazorWorker.Extensions.JSRuntime + for using the specially crafted IJSRuntime that can be used with workers. + +

+ @foreach (var item in new string[] { "Persistant startup class", "Startup class disposed with service" }) + { +
+ + +
+ } +

+
+
+ Output: +
+
+            @output
+
+
+
+ +
+
+@code { + + string output = ""; + IWorker worker; + IWorkerBackgroundService startupService; + string canDisposeWorker => worker == null ? null : "disabled"; + string RunDisabled => Running ? "disabled" : null; + bool Running = false; + string RadioValue = "Persistant startup class"; + void RadioSelection(ChangeEventArgs args) + { + RadioValue = args.Value.ToString(); + } + public async Task OnClick(EventArgs _) + { + Running = true; + //output = ""; + var rn = Environment.NewLine; + try + { + + if (worker == null) + { + worker = await workerFactory.CreateAsync(); + } + + var sw = new System.Diagnostics.Stopwatch(); + IWorkerBackgroundService myIocService; + var persistedStartup = RadioValue == "Persistant startup class"; + + if (persistedStartup) + { + + if (startupService == null) + { + output = $"{rn}{LogDate()} Creating background service..."; + StateHasChanged(); + + sw.Start(); + startupService = await worker.CreateBackgroundServiceAsync(); + + output += $"{rn}{LogDate()} Background service created in {sw.ElapsedMilliseconds}ms"; + StateHasChanged(); + } + output += $"{rn}{LogDate()} Resolving instance..."; + myIocService = await startupService.CreateBackgroundServiceAsync(startup => startup.Resolve()); + } + else + { + output += $"{rn}{LogDate()} Resolving Startup & instance..."; + myIocService = await worker.CreateBackgroundServiceUsingFactoryAsync(startup => startup.Resolve()); + } + + await using (myIocService) + { + await myIocService.RegisterEventListenerAsync(nameof(MyIocService.FiveCalled), + (object s, int five) => + { + output += $"{rn}{LogDate()} OnFiveCalled: {five}"; + StateHasChanged(); + }); + output += $"{rn}{LogDate()} Calling Five()..."; + output += $"{rn}{LogDate()} Five() = {await myIocService.RunAsync(s => s.Five())}"; + } + + StateHasChanged(); + + } + catch (Exception e) + { + output += $"{rn}Error = {e}"; + } + finally + { + Running = false; + } + } + + public async Task OnDisposeWorker() + { + await worker.DisposeAsync(); + worker = null; + startupService = null; + } + + private string LogDate() + { + return DateTime.Now.ToString("HH:mm:ss:fff"); + } +} \ No newline at end of file diff --git a/src/BlazorWorker.Extensions.JSRuntime/BlazorWorker.Core.xml b/src/BlazorWorker.Extensions.JSRuntime/BlazorWorker.Core.xml deleted file mode 100644 index db5a7ff..0000000 --- a/src/BlazorWorker.Extensions.JSRuntime/BlazorWorker.Core.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - BlazorWorker.Extensions.JSRuntime - - - - diff --git a/src/BlazorWorker.Extensions.JSRuntime/BlazorWorker.Extensions.JSRuntime.csproj b/src/BlazorWorker.Extensions.JSRuntime/BlazorWorker.Extensions.JSRuntime.csproj index f9dac5a..658622e 100644 --- a/src/BlazorWorker.Extensions.JSRuntime/BlazorWorker.Extensions.JSRuntime.csproj +++ b/src/BlazorWorker.Extensions.JSRuntime/BlazorWorker.Extensions.JSRuntime.csproj @@ -1,7 +1,7 @@ - + - net7.0 + net7.0;net8.0 Tor Knutsson (Tewr) BlazorWorker MIT @@ -11,9 +11,9 @@ WebWorker Worker Process Threading Multithreading Blazor Isolation Tewr.BlazorWorker.Extensions.JSRuntime Debug;Release;Nuget - 4.0.0-preview + 4.0.0-preview2 4.0.0 - BlazorWorker.Core.xml + BlazorWorker.Extensions.JSRuntime.xml icon.png false .Net6 Support @@ -21,39 +21,36 @@ + + - - - - - - - - - - - - + + + true + + + + + + + - - - - - - + + true - + + 1701;1702;1591;CA1416 + + + - - - diff --git a/src/BlazorWorker.Extensions.JSRuntime/BlazorWorker.Extensions.JSRuntime.xml b/src/BlazorWorker.Extensions.JSRuntime/BlazorWorker.Extensions.JSRuntime.xml new file mode 100644 index 0000000..6f85a23 --- /dev/null +++ b/src/BlazorWorker.Extensions.JSRuntime/BlazorWorker.Extensions.JSRuntime.xml @@ -0,0 +1,84 @@ + + + + BlazorWorker.Extensions.JSRuntime + + + + + IJSRuntime implementation for use in a worker process + + + + + Serializer that will be used + + + + + The serializer options to be used for the underlying serializer + + + + + Creates a new JSRuntime + + + + + Invokes a method defined on the worker globalThis (self) object + + expected return type + js method name + JSON serializable arguments to send to the js method + + + + + Invokes a method defined on the worker globalThis (self) object asynchronically + + expected return type + js method name + JSON serializable arguments to send to the js method + + + + + Imports locally hosted module scripts + + + + + + + Invokes a method defined on the worker globalThis / self object + + + + JSON serialized parameters + + + + + Asynchronically Invokes a method defined on the worker globalThis / self object + + + + JSON serialized parameters + + + + + Checks if the specified object path is defined using the self / globalThis object as root. + + + + + + + Prepending the specified with the base path of the application, invokes the importScripts() method of the WorkerGlobalScope interface, which synchronously imports one or more scripts into the worker's scope. + + + + + diff --git a/src/BlazorWorker.Extensions.JSRuntime/BlazorWorkerJSRuntime.cs b/src/BlazorWorker.Extensions.JSRuntime/BlazorWorkerJSRuntime.cs index 0905ece..e55458c 100644 --- a/src/BlazorWorker.Extensions.JSRuntime/BlazorWorkerJSRuntime.cs +++ b/src/BlazorWorker.Extensions.JSRuntime/BlazorWorkerJSRuntime.cs @@ -2,27 +2,68 @@ using Microsoft.JSInterop; using System; using System.Linq; +using System.Runtime.InteropServices.JavaScript; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; namespace BlazorWorker.Extensions.JSRuntime { - public class BlazorWorkerJSRuntime : IJSRuntime, IJSInProcessRuntime + /// + /// IJSRuntime implementation for use in a worker process + /// + public partial class BlazorWorkerJSRuntime : IJSRuntime, IJSInProcessRuntime { private static bool isJsInitialized; + /// + /// Serializer that will be used + /// public IBlazorWorkerJSRuntimeSerializer Serializer { get; set; } + /// + /// The serializer options to be used for the underlying serializer + /// + public JsonSerializerOptions SerializerOptions { get; } + + /// + /// Creates a new JSRuntime + /// public BlazorWorkerJSRuntime() { - this.Serializer = new DefaultBlazorWorkerJSRuntimeSerializer(this); + + SerializerOptions = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = { + { new DotNetObjectReferenceJsonConverterFactory(this) } +} + }; + + this.Serializer = new DefaultBlazorWorkerJSRuntimeSerializer(SerializerOptions); } + /// + /// Invokes a method defined on the worker globalThis (self) object + /// + /// expected return type + /// js method name + /// JSON serializable arguments to send to the js method + /// public T Invoke(string identifier, params object[] args) { - return JSInvokeService.Invoke(identifier, args); + var resultString = JSInvokeService.WorkerInvoke(identifier, Serialize(args)); + + return this.Serializer.Deserialize(resultString); } + /// + /// Invokes a method defined on the worker globalThis (self) object asynchronically + /// + /// expected return type + /// js method name + /// JSON serializable arguments to send to the js method + /// public ValueTask InvokeAsync(string identifier, object[] args) { return InvokeAsync(identifier, CancellationToken.None, args ?? new object[] { }); @@ -49,36 +90,28 @@ public async ValueTask InvokeAsync( object[] args) { var serializedArgs = Serialize(args); - object resultObj; - - try - { - EnsureInitialized(); - - resultObj = await JSInvokeService.InvokeAsync(identifier, - cancellationToken, serializedArgs, "BlazorWorkerJSRuntimeSerializer"); - } - catch (System.AggregateException e) when (e.InnerException is JSInvokeException) - { - throw e.InnerException; - } + string resultObj; + await EnsureInitialized(); + + resultObj = await JSInvokeService.WorkerInvokeAsync(identifier, serializedArgs); + + cancellationToken.ThrowIfCancellationRequested(); - //Console.WriteLine($"{nameof(BlazorWorkerJSRuntime)}.{nameof(InvokeAsync)}({identifier}): deserializing result: {resultObj?.ToString()} "); - var result = Deserialize(resultObj as string); - //Console.WriteLine($"{nameof(BlazorWorkerJSRuntime)}.{nameof(InvokeAsync)}({identifier}): returning deserialized result of type {(result?.GetType().ToString() ?? "(null)")}: {result?.ToString()} "); + var result = Deserialize(resultObj); return result; } - private static void EnsureInitialized() + private static async Task EnsureInitialized() { if (!isJsInitialized && !JSInvokeService.IsObjectDefined("BlazorWorkerJSRuntimeSerializer")) { - JSInvokeService.ImportLocalScripts("_content/Tewr.BlazorWorker.Extensions.JSRuntime/BlazorWorkerJSRuntime.js"); + await JSInvokeService.ImportLocalScripts("_content/Tewr.BlazorWorker.Extensions.JSRuntime/BlazorWorkerJSRuntime.js"); isJsInitialized = true; } } + [JSExport] public static string InvokeMethod(string objectInstanceId, string argsString) { #if DEBUG diff --git a/src/BlazorWorker.Extensions.JSRuntime/BlazorWorkerJsRuntimeSetupExtensions.cs b/src/BlazorWorker.Extensions.JSRuntime/BlazorWorkerJsRuntimeSetupExtensions.cs index cc71a0f..1b09c05 100644 --- a/src/BlazorWorker.Extensions.JSRuntime/BlazorWorkerJsRuntimeSetupExtensions.cs +++ b/src/BlazorWorker.Extensions.JSRuntime/BlazorWorkerJsRuntimeSetupExtensions.cs @@ -1,25 +1,28 @@ -using BlazorWorker.Core; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Microsoft.JSInterop; +using System; +using System.Text.Json; namespace BlazorWorker.Extensions.JSRuntime { public static class BlazorWorkerJsRuntimeSetupExtensions { - public static IServiceCollection AddBlazorWorkerJsRuntime(this IServiceCollection source) + public static IServiceCollection AddBlazorWorkerJsRuntime(this IServiceCollection source, Action optionsModifier = null) { - source.AddSingleton(); - source.AddSingleton(); + source.AddSingleton(CreateBlazorWorkerJSRuntime(optionsModifier)); return source; } - public static WorkerInitOptions AddBlazorWorkerJsRuntime(this WorkerInitOptions source) - { - source.AddAssemblyOf() - .AddAssemblyOf() - .AddAssemblyOf() - .AddAssemblyOf(); - return source; + private static Func CreateBlazorWorkerJSRuntime(Action optionsModifier) { + + var instance = new BlazorWorkerJSRuntime(); + + if (optionsModifier != null) + { + optionsModifier(instance.SerializerOptions); + } + + return _ => instance; } } } diff --git a/src/BlazorWorker.Extensions.JSRuntime/DefaultBlazorWorkerJSRuntimeSerializer.cs b/src/BlazorWorker.Extensions.JSRuntime/DefaultBlazorWorkerJSRuntimeSerializer.cs index 1d0e363..e92dc16 100644 --- a/src/BlazorWorker.Extensions.JSRuntime/DefaultBlazorWorkerJSRuntimeSerializer.cs +++ b/src/BlazorWorker.Extensions.JSRuntime/DefaultBlazorWorkerJSRuntimeSerializer.cs @@ -1,7 +1,5 @@ using Microsoft.JSInterop; -using System; using System.Text.Json; -using System.Text.Json.Serialization; namespace BlazorWorker.Extensions.JSRuntime { @@ -9,15 +7,9 @@ internal class DefaultBlazorWorkerJSRuntimeSerializer : IBlazorWorkerJSRuntimeSe { private readonly JsonSerializerOptions options; - public DefaultBlazorWorkerJSRuntimeSerializer(IJSRuntime jSRuntime) + public DefaultBlazorWorkerJSRuntimeSerializer(JsonSerializerOptions options) { - options = new JsonSerializerOptions - { - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - Converters = { - { new DotNetObjectReferenceJsonConverterFactory(jSRuntime) } - } - }; + this.options = options; } public T Deserialize(string serializedObject) diff --git a/src/BlazorWorker.Extensions.JSRuntime/DotNetObjectReferenceTracker.cs b/src/BlazorWorker.Extensions.JSRuntime/DotNetObjectReferenceTracker.cs index ac9d959..05f5480 100644 --- a/src/BlazorWorker.Extensions.JSRuntime/DotNetObjectReferenceTracker.cs +++ b/src/BlazorWorker.Extensions.JSRuntime/DotNetObjectReferenceTracker.cs @@ -26,7 +26,7 @@ internal static object GetObjectReference(long dotNetObjectId) return objectTracker.InternalGetObjectReference(dotNetObjectId); } - internal static long TrackObjectReference(DotNetObjectReference value) where T: class + internal static long TrackObjectReference(DotNetObjectReference value) where T : class { return objectTracker.InternalTrackObjectReference(value); } @@ -54,7 +54,7 @@ internal class TrackerJsRuntime : Microsoft.JSInterop.JSRuntime static TrackerJsRuntime() { var targetType = typeof(Microsoft.JSInterop.JSRuntime); - var name = nameof(DotNetObjectReferenceTracker.GetObjectReference); + var name = nameof(GetObjectReference); var firstArgType = typeof(long); var methodInfo = targetType.GetRuntimeMethods().FirstOrDefault(methodInfo => !methodInfo.IsPublic && @@ -75,7 +75,7 @@ public object InternalGetObjectReference(long dotNetObjectId) return GetObjectReferenceMethod.Invoke(this, new object[] { dotNetObjectId }); } - public long InternalTrackObjectReference(DotNetObjectReference value) where T : class + public long InternalTrackObjectReference(DotNetObjectReference value) where T : class { var method = TrackObjectReferenceDelegates .GetDelegate, T, DotNetObjectReference> @@ -85,7 +85,7 @@ public long InternalTrackObjectReference(DotNetObjectReference value) whe } #region Unsupported methods - + protected override void BeginInvokeJS(long taskId, string identifier, string argsJson) { throw new NotSupportedException(); diff --git a/src/BlazorWorker.Extensions.JSRuntime/JSInvokeService.cs b/src/BlazorWorker.Extensions.JSRuntime/JSInvokeService.cs new file mode 100644 index 0000000..6ceae7b --- /dev/null +++ b/src/BlazorWorker.Extensions.JSRuntime/JSInvokeService.cs @@ -0,0 +1,61 @@ +using System.Runtime.InteropServices.JavaScript; +using System.Threading.Tasks; + +namespace BlazorWorker.Extensions.JSRuntime +{ + public partial class JSInvokeService + { + /// + /// Imports locally hosted module scripts + /// + /// + /// + public static Task ImportLocalScripts(params string[] relativeUrls) + => PrivateImportLocalScripts(relativeUrls); + + /// + /// Invokes a method defined on the worker globalThis / self object + /// + /// + /// + /// JSON serialized parameters + /// + public static string WorkerInvoke(string method, string args) + => (string) PrivateWorkerInvoke(method, args); + + /// + /// Asynchronically Invokes a method defined on the worker globalThis / self object + /// + /// + /// + /// JSON serialized parameters + /// + public static async Task WorkerInvokeAsync(string method, string args) + => (await PrivateWorkerInvokeAsync(method, args)); + + #region Generated methods + + /// + /// Checks if the specified object path is defined using the self / globalThis object as root. + /// + /// + /// + [JSImport("IsObjectDefined", "BlazorWorker.js")] + public static partial bool IsObjectDefined(string objectPath); + + /// + /// Prepending the specified with the base path of the application, invokes the importScripts() method of the WorkerGlobalScope interface, which synchronously imports one or more scripts into the worker's scope. + /// + /// + [JSImport("ImportLocalScripts", "BlazorWorker.js")] + private static partial Task PrivateImportLocalScripts(string[] relativeUrls); + + [JSImport("WorkerInvokeAsync", "BlazorWorkerJSRuntime.js")] + private static partial Task PrivateWorkerInvokeAsync(string method, string args); + + [JSImport("WorkerInvoke", "BlazorWorkerJSRuntime.js")] + private static partial string PrivateWorkerInvoke(string method, string args); + + #endregion + } +} diff --git a/src/BlazorWorker.Extensions.JSRuntime/wwwroot/BlazorWorkerJSRuntime.js b/src/BlazorWorker.Extensions.JSRuntime/wwwroot/BlazorWorkerJSRuntime.js index 3a76292..76fd5e0 100644 --- a/src/BlazorWorker.Extensions.JSRuntime/wwwroot/BlazorWorkerJSRuntime.js +++ b/src/BlazorWorker.Extensions.JSRuntime/wwwroot/BlazorWorkerJSRuntime.js @@ -1,7 +1,8 @@ class DotNetObjectProxy { constructor(id) { this.__dotNetObject = id; - this.serializer = self.jsRuntimeSerializers.get('BlazorWorkerJSRuntimeSerializer'); + this.serializer = self.jsRuntimeSerializer; + this.blazorWorkerJSRuntime = self.BlazorWorker.getAssemblyExports("BlazorWorker.Extensions.JSRuntime").BlazorWorkerJSRuntime; } invokeMethodAsync(methodName, ...methodArgs) { @@ -11,7 +12,7 @@ methodName, methodargs: methodArgs || [] }); - var result = self.Module.mono_call_static_method("[BlazorWorker.Extensions.JSRuntime]BlazorWorker.Extensions.JSRuntime.BlazorWorkerJSRuntime:InvokeMethod", this.__dotNetObject, argsString); + var result = this.blazorWorkerJSRuntime.InvokeMethod(this.__dotNetObject, argsString); resolve(result); } catch (e) { reject(e); @@ -23,11 +24,13 @@ class BlazorWorkerJSRuntimeSerializer { constructor() { - this.baseSerializer = self.jsRuntimeSerializers.get('nativejson'); + this.baseSerializer = { + serialize: o => JSON.stringify(o), + deserialize: s => JSON.parse(s) + }; } serialize = (o) => this.baseSerializer.serialize(o); - deserialize = (s) => { let deserializedObj = this.baseSerializer.deserialize(s); @@ -56,4 +59,34 @@ class BlazorWorkerJSRuntimeSerializer { } }; -self.jsRuntimeSerializers.set('BlazorWorkerJSRuntimeSerializer', new BlazorWorkerJSRuntimeSerializer()); \ No newline at end of file +const serializer = new BlazorWorkerJSRuntimeSerializer(); + +const workerInvokeAsync = async function (method, argsString) { + + const methodHandle = self.BlazorWorker.getChildFromDotNotation(method); + + if (methodHandle === self.BlazorWorker.empty) { + throw new Error(`workerInvokeAsync: Method '${method}' not defined`); + } + + const argsArray = serializer.deserialize(argsString); + const result = await methodHandle(...argsArray); + return serializer.serialize(result); +} + +const workerInvoke = function (method, argsString) { + + const methodHandle = self.BlazorWorker.getChildFromDotNotation(method); + if (methodHandle === self.BlazorWorker.empty) { + throw new Error(`workerInvoke: Method '${method}' not defined`); + } + + const argsArray = serializer.deserialize(argsString); + const result = methodHandle(...argsArray); + return serializer.serialize(result); +} + +self.BlazorWorker.setModuleImports("BlazorWorkerJSRuntime.js", { + WorkerInvokeAsync: workerInvokeAsync, + WorkerInvoke: workerInvoke +}); \ No newline at end of file diff --git a/src/BlazorWorker.ServiceFactory/BlazorWorker.BackgroundServiceFactory.csproj b/src/BlazorWorker.ServiceFactory/BlazorWorker.BackgroundServiceFactory.csproj index 196ad0b..24d4077 100644 --- a/src/BlazorWorker.ServiceFactory/BlazorWorker.BackgroundServiceFactory.csproj +++ b/src/BlazorWorker.ServiceFactory/BlazorWorker.BackgroundServiceFactory.csproj @@ -58,6 +58,10 @@ BlazorWorker.BackgroundServiceFactory.xml + + 1701;1702;1591;CA1416 + + diff --git a/src/BlazorWorker.ServiceFactory/WorkerBackgroundServiceExtensions.cs b/src/BlazorWorker.ServiceFactory/WorkerBackgroundServiceExtensions.cs index 48d3dd2..9d7c686 100644 --- a/src/BlazorWorker.ServiceFactory/WorkerBackgroundServiceExtensions.cs +++ b/src/BlazorWorker.ServiceFactory/WorkerBackgroundServiceExtensions.cs @@ -30,7 +30,7 @@ public static async Task> CreateBackgroundServiceAsy var proxy = new WorkerBackgroundServiceProxy(webWorkerProxy, new WebWorkerOptions()); if (workerInitOptions == null) { - workerInitOptions = new WorkerInitOptions().AddAssemblyOf(); + workerInitOptions = new WorkerInitOptions(); } await proxy.InitAsync(workerInitOptions); @@ -64,11 +64,7 @@ public static async Task> CreateBackgroundSer } var workerInitOptions = new WorkerInitOptions(); - if (workerInitOptionsModifier == null) - { - workerInitOptions.AddAssemblyOf(); - } - else + if (workerInitOptionsModifier != null) { workerInitOptionsModifier(workerInitOptions); } diff --git a/src/BlazorWorker.ServiceFactory/WorkerBackgroundServiceProxy.cs b/src/BlazorWorker.ServiceFactory/WorkerBackgroundServiceProxy.cs index e593340..0ce3c91 100644 --- a/src/BlazorWorker.ServiceFactory/WorkerBackgroundServiceProxy.cs +++ b/src/BlazorWorker.ServiceFactory/WorkerBackgroundServiceProxy.cs @@ -12,16 +12,12 @@ namespace BlazorWorker.BackgroundServiceFactory internal class WorkerBackgroundServiceProxy { private static long idSource; internal static readonly MethodIdentifier InitEndPoint; - //internal static readonly string EndInvokeCallBackEndpoint; public static long GetNextId() => ++idSource; static WorkerBackgroundServiceProxy() { var wim = typeof(WorkerInstanceManager); InitEndPoint = MonoTypeHelper.GetStaticMethodId(nameof(WorkerInstanceManager.Init)); - /*EndInvokeCallBackEndpoint = - MonoTypeHelper.GetStaticMethodId(nameof(JSInvokeService.EndInvokeCallBack)); - */ } } diff --git a/src/BlazorWorker.WorkerBackgroundService/BlazorWorker.WorkerBackgroundService.csproj b/src/BlazorWorker.WorkerBackgroundService/BlazorWorker.WorkerBackgroundService.csproj index 53018bc..658866f 100644 --- a/src/BlazorWorker.WorkerBackgroundService/BlazorWorker.WorkerBackgroundService.csproj +++ b/src/BlazorWorker.WorkerBackgroundService/BlazorWorker.WorkerBackgroundService.csproj @@ -11,6 +11,10 @@ BlazorWorker.WorkerBackgroundService.xml + + + 1701;1702;1591;CA1416 + diff --git a/src/BlazorWorker.WorkerBackgroundService/InitWorkerInstanceException.cs b/src/BlazorWorker.WorkerBackgroundService/InitWorkerInstanceException.cs deleted file mode 100644 index 6d12e0d..0000000 --- a/src/BlazorWorker.WorkerBackgroundService/InitWorkerInstanceException.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Runtime.Serialization; - -namespace BlazorWorker.WorkerBackgroundService -{ - [Serializable] - public class InitWorkerInstanceException : Exception - { - public InitWorkerInstanceException() - { - } - - public InitWorkerInstanceException(string message) : base(message) - { - } - - public InitWorkerInstanceException(string message, Exception innerException) : base(message, innerException) - { - } - - protected InitWorkerInstanceException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } - } -} \ No newline at end of file diff --git a/src/BlazorWorker.WorkerBackgroundService/WorkerInstanceManager.cs b/src/BlazorWorker.WorkerBackgroundService/WorkerInstanceManager.cs index da75f76..79e943f 100644 --- a/src/BlazorWorker.WorkerBackgroundService/WorkerInstanceManager.cs +++ b/src/BlazorWorker.WorkerBackgroundService/WorkerInstanceManager.cs @@ -3,13 +3,13 @@ using System; using System.Collections.Concurrent; using System.Linq.Expressions; -#if NET7_0_OR_GREATER using System.Runtime.InteropServices.JavaScript; -#endif +using System.Runtime.Versioning; using System.Threading.Tasks; namespace BlazorWorker.WorkerBackgroundService { + [SupportedOSPlatform("browser")] public partial class WorkerInstanceManager { private readonly ConcurrentDictionary events = @@ -44,9 +44,8 @@ public WorkerInstanceManager() this.messageHandler = messageHandlerRegistry.GetRegistryForInstance(this); } -#if NET7_0_OR_GREATER + [JSExport] -#endif public static void Init() { MessageService.Message += Instance.OnMessage; Instance.PostObject(new InitWorkerComplete()); diff --git a/src/BlazorWorker.WorkerCore/BlazorWorker.WorkerCore.csproj b/src/BlazorWorker.WorkerCore/BlazorWorker.WorkerCore.csproj index 501da70..c12a490 100644 --- a/src/BlazorWorker.WorkerCore/BlazorWorker.WorkerCore.csproj +++ b/src/BlazorWorker.WorkerCore/BlazorWorker.WorkerCore.csproj @@ -14,6 +14,10 @@ BlazorWorker.WorkerCore.xml Exe + + + 1701;1702;1591;CA1416 + diff --git a/src/BlazorWorker.WorkerCore/BlazorWorker.WorkerCore.xml b/src/BlazorWorker.WorkerCore/BlazorWorker.WorkerCore.xml index ecfa1ac..113b2fa 100644 --- a/src/BlazorWorker.WorkerCore/BlazorWorker.WorkerCore.xml +++ b/src/BlazorWorker.WorkerCore/BlazorWorker.WorkerCore.xml @@ -4,12 +4,6 @@ BlazorWorker.WorkerCore - - - Prepending the specified with the base path of the application, invokes the importScripts() method of the WorkerGlobalScope interface, which synchronously imports one or more scripts into the worker's scope. - - - Simple static message service that runs in the worker thread. diff --git a/src/BlazorWorker.WorkerCore/JSInvokeException.cs b/src/BlazorWorker.WorkerCore/JSInvokeException.cs deleted file mode 100644 index fd72c1e..0000000 --- a/src/BlazorWorker.WorkerCore/JSInvokeException.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Runtime.Serialization; - -namespace BlazorWorker.WorkerCore -{ - [Serializable] - public class JSInvokeException : Exception - { - public JSInvokeException(string message): base(message) - { - } - - public JSInvokeException(string message, Exception innerException) : base(message, innerException) - { - } - - protected JSInvokeException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } - } -} \ No newline at end of file diff --git a/src/BlazorWorker.WorkerCore/JSInvokeService.cs b/src/BlazorWorker.WorkerCore/JSInvokeService.cs deleted file mode 100644 index 5d94c0e..0000000 --- a/src/BlazorWorker.WorkerCore/JSInvokeService.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Runtime.InteropServices.JavaScript; -using System.Threading; -using System.Threading.Tasks; - -namespace BlazorWorker.WorkerCore -{ - - public partial class JSInvokeService - { - - public static void ImportLocalScripts(params string[] relativeUrls) - { - PrivateImportLocalScripts(relativeUrls); - } - - /// - /// Prepending the specified with the base path of the application, invokes the importScripts() method of the WorkerGlobalScope interface, which synchronously imports one or more scripts into the worker's scope. - /// - /// - [JSImport("importLocalScripts")] - private static partial void PrivateImportLocalScripts(string[] relativeUrls); - - } -} diff --git a/src/BlazorWorker.WorkerCore/SimpleInstanceService/SimpleInstanceService.cs b/src/BlazorWorker.WorkerCore/SimpleInstanceService/SimpleInstanceService.cs index 45ddbf6..675f0ba 100644 --- a/src/BlazorWorker.WorkerCore/SimpleInstanceService/SimpleInstanceService.cs +++ b/src/BlazorWorker.WorkerCore/SimpleInstanceService/SimpleInstanceService.cs @@ -5,9 +5,11 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.JavaScript; +using System.Runtime.Versioning; namespace BlazorWorker.WorkerCore.SimpleInstanceService { + [SupportedOSPlatform("browser")] public partial class SimpleInstanceService { diff --git a/src/BlazorWorker.WorkerCore/WorkerException.cs b/src/BlazorWorker.WorkerCore/WorkerException.cs deleted file mode 100644 index e4fabd0..0000000 --- a/src/BlazorWorker.WorkerCore/WorkerException.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Runtime.Serialization; - -namespace BlazorWorker.WorkerCore -{ - [Serializable] - public class WorkerException : Exception - { - public WorkerException(string message) : base(message) - { - } - - public WorkerException(string message, Exception innerException) : base(message, innerException) - { - } - - protected WorkerException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } - } -} \ No newline at end of file diff --git a/src/BlazorWorker/BlazorWorker.Core.csproj b/src/BlazorWorker/BlazorWorker.Core.csproj index 41d05b7..9d6f935 100644 --- a/src/BlazorWorker/BlazorWorker.Core.csproj +++ b/src/BlazorWorker/BlazorWorker.Core.csproj @@ -47,6 +47,10 @@ $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage true + + + 1701;1702;1591;CA1416 + diff --git a/src/BlazorWorker/BlazorWorker.js b/src/BlazorWorker/BlazorWorker.js index 99d213d..c7951f5 100644 --- a/src/BlazorWorker/BlazorWorker.js +++ b/src/BlazorWorker/BlazorWorker.js @@ -78,6 +78,8 @@ window.BlazorWorker = function () { const getChildFromDotNotation = (member, root) => member.split(".").reduce((m, prop) => Object.hasOwnProperty.call(m, prop) ? m[prop] : empty, root || self); + + //TODO: This call could/should be session cached. But will the built-in blazor fetch service worker override // (PWA et al) do this already if configured ? fetch(`${initConf.appRoot}/${initConf.blazorBoot}`) @@ -161,23 +163,32 @@ window.BlazorWorker = function () { const { dotnet } = await import(`${initConf.appRoot}/${initConf.wasmRoot}/${dotnetjsfilename}`); const { setModuleImports, getAssemblyExports } = await dotnet - .withConfig({ - // https://github.com/dotnet/runtime/blob/955604c6620d0eaf9a10b4591449e377a6faa7d3/src/mono/browser/runtime/dotnet.d.ts#L20 - // as well as - // https://github.com/dotnet/runtime/blob/955604c6620d0eaf9a10b4591449e377a6faa7d3/src/mono/browser/runtime/dotnet.d.ts#L97 - err: (e) => { console.error(`WORKER ${initConf.workerId}: ${(e || "(null)")}`) }, - out: (o) => { console.info(`WORKER ${initConf.workerId}: ${(o || "(null)")}`) } - }) - .withDiagnosticTracing(false) + .withDiagnosticTracing(initConf.debug) .withEnvironmentVariables(initConf.envMap) .create(); setModuleImports('BlazorWorker.js', { PostMessage: (messagecontent) => { self.postMessage(messagecontent); + }, + + ImportLocalScripts: async (urls) => { + await self.importLocalScripts(urls); + }, + + IsObjectDefined: (workerScopeObject) => { + return self.isObjectDefined(workerScopeObject); } }); + + self.BlazorWorker = { + getChildFromDotNotation, + getAssemblyExports, + setModuleImports, + empty + }; + const getMethodFromMethodIdentifier = async function (methodIdentifier) { const exports = await getAssemblyExports(methodIdentifier.assemblyName); const method = getChildFromDotNotation(methodIdentifier.fullMethodName, exports); @@ -197,9 +208,12 @@ window.BlazorWorker = function () { const empty = {}; - // Import script from a path relative to approot - self.importLocalScripts = (...urls) => { - self.importScripts(urls.map(url => initConf.appRoot + (url.startsWith('/') ? '' : '/') + url)); + // Import module script from a path relative to approot + self.importLocalScripts = async (urls) => { + const mappedUrls = urls.map(url => initConf.appRoot + (url.startsWith('/') ? '' : '/') + url); + for (const url of mappedUrls) { + await import(url); + } }; self.isObjectDefined = (workerScopeObject) => { @@ -218,9 +232,7 @@ window.BlazorWorker = function () { const initConf = { appRoot: appRoot, workerId:id, - //DependentAssemblyFilenames: initOptions.dependentAssemblyFilenames, runtimePreprocessorSymbols: initOptions.runtimePreprocessorSymbols || {}, - //deploy_prefix: initOptions.deployPrefix, messageEndPoint: initOptions.messageEndPoint, initEndPoint: initOptions.initEndPoint, endInvokeCallBackEndpoint: initOptions.endInvokeCallBackEndpoint, diff --git a/src/BlazorWorker/CoreInstanceService/CoreInstanceService.cs b/src/BlazorWorker/CoreInstanceService/CoreInstanceService.cs index 81b574a..b7de4ff 100644 --- a/src/BlazorWorker/CoreInstanceService/CoreInstanceService.cs +++ b/src/BlazorWorker/CoreInstanceService/CoreInstanceService.cs @@ -64,12 +64,6 @@ public async Task CreateInstance(Type t, WorkerInitOptions opti if (options == null) { options = new WorkerInitOptions(); - options.AddAssemblyOfType(t); - } - - if (options.UseConventionalServiceAssembly) - { - options.AddAssemblyOfType(t); } await this.simpleInstanceServiceProxy.InitializeAsync( diff --git a/src/BlazorWorker/SimpleInstanceService/SimpleInstanceServiceProxy.cs b/src/BlazorWorker/SimpleInstanceService/SimpleInstanceServiceProxy.cs index 3a59883..4c948db 100644 --- a/src/BlazorWorker/SimpleInstanceService/SimpleInstanceServiceProxy.cs +++ b/src/BlazorWorker/SimpleInstanceService/SimpleInstanceServiceProxy.cs @@ -9,14 +9,10 @@ namespace BlazorWorker.Core.SimpleInstanceService public class SimpleInstanceServiceProxy : ISimpleInstanceService { private readonly IWorker worker; - private readonly TaskRegister disposeResultRegister = - new TaskRegister(); - private readonly TaskRegister initInstanceRegister = - new TaskRegister(); + private readonly TaskRegister disposeResultRegister = new(); + private readonly TaskRegister initInstanceRegister = new(); private TaskCompletionSource initWorker; - private long callIdSource; - public bool IsInitialized { get; internal set; } public SimpleInstanceServiceProxy(IWorker worker)