dotnet/aspnetcore

IJSInProcessRuntime and IJSUnmarshalledRuntime don't work in Blazor Server

sps014 opened this issue · 4 comments

The following JSInterop code works blazor Web Assembly but exact same code doesn't work on Blazor Server

public static async ValueTask InitAsync(IJSRuntime jsRuntime)
{
            Runtime = jsRuntime as IJSInProcessRuntime; //in server this cast is null but in wasm works fine
            _moduleTask = new(() => Runtime.InvokeAsync<IJSUnmarshalledObjectReference>(
               "import", "./_content/BlazorBindGen/blazorbindgen.js").AsTask()); 
            Module = await _moduleTask.Value;
}

I am missing something?

@sps014 thanks for contacting us.

That's by design. Blazor Server runs in a separate process from the Browser. That's why we recommend using IJSRuntime and leaving IJSUnmarshalledRuntime as an optional optimization specific to webassembly.

That's by design. Blazor Server runs in a separate process from the Browser. That's why we recommend using IJSRuntime and leaving IJSUnmarshalledRuntime as an optional optimization specific to webassembly.

I see, but IJSRuntime is limited in functionality and does not contain non async variant of Invoke Methods.
Is there any plan to extend IJSRuntime in future to add more capabilities ?

@sps014 IJSRuntime only contains async methods because in general we can't guarantee that there is synchronous communication between the browser and the C# runtime, that's why the default implementation is async only, because that's the minimum all platforms can support.

The unmarshalled runtime is specific to webassembly and the communication channel with the browser. There is an IInProcesJSRuntime that offers synchronous variants, but again, only webassembly implements it.

The reality is that unless you are doing something very specific you aren't likely going to see any benefits from using the more specific runtimes, so our recommendation is that you rely only on IJSRuntime and only optionally use other JS interop interfaces with a type check ahead of time to ensure its available.

thanks