Search code examples
c#blazor-webassemblywebassemblyuno-platformgrpc-web

Cannot create GrpcChannel in Uno Platform WebAssembly (System.NullReferenceException)


I am trying to do a sample of Uno Platform using gRPC-Web.

Therefore I got inspired by the content provided by this article. I followed the instructions of the article and created a BlazorApp which used a weather service with gRPC-Web. After that I also included an other service, the counter service, as seen in this gRPC-Web example.

After everthing was working, I added a Uno Platform WebAssembly app to replace the BlazorApp client.

Current Problem:

When trying to create a GrpcChannel the application gets a System.NullReferenceException.

The code snippet for creating the channel looks like this:

var baseUri = "https://localhost:44366";
var channel = GrpcChannel.ForAddress(baseUri, new GrpcChannelOptions());

This is exactly the same code as used in the BlazorApp.

The sample code for the BlazorApp and the Uno Platform WebAssembly can be found in this repository.

Any idea/suggestion/help would be appreciated.


Solution

  • Ok I analyzed your code and I found 4 problems in your code:

    1. You were using the Blazor IoC Container. Uno is not designed to use it out-of-the-box. There some ways to use a container, but there's more work to do. To fix this, I simply moved the gRPC service initialization into the MainPage.xaml.cs instead. That's not production quality, but it serves the purpose of demoing gRPC.
    2. You were calling the SYNC version of .IncrementCount(). This is not possible on WASM since it's not possible to block the main thread in WASM (actually, it's possible, but you need to use primitives hidden deep in JavaScript and it won't solve your problem anyway). That's why on Blazor you need to call .IncrementCountAsync(). The same requirements are present on WASM.
    3. The XAML of your page were using a <Grid> without any rows, so each elements were drawn one over the other. I replaced it with a <StackPanel> to have a better result.
    4. Is was required to activate CORS on the server because the host name + port is slightly different.

    I published a working version on a Fork I did of your project IT WORKS!!