Reputation: 63
In my .NET 8 Blazor Web App with rendermode Auto I've been using server rendering so far. While trying out WASM I noticed I can't just inject server service instances. This is because it uses its own runtime (Porject.Client) with its own DI.
I can't create the service in the client because it's a wrapper to a performance demanding external executable.
I could of course make the service an API, but what would be the Blazor way of doing this?
To reduce WASM size and not expose the service code I already made an interface for it in the client.
Upvotes: 0
Views: 138
Reputation: 28192
In my opinion, the best way to achieve this is creating a API controller and the blazor webassembly use the httpclient to call this API to get the data and bind to the model.
HttpClient and JSON helpers (System.Net.Http.Json.HttpClientJsonExtensions) are also used to call third-party web API endpoints. HttpClient is implemented using the browser's Fetch API and is subject to its limitations, including enforcement of the same-origin policy, which is discussed later in this article in the Cross-Origin Resource Sharing (CORS) section.
The client's base address is set to the originating server's address.
More details, you could refer to below codes:
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddScoped(sp =>
new HttpClient
{
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
});
await builder.Build().RunAsync();
Then you could inject it and use it like below:
Inject the service:
@using System.Net.Http
@inject HttpClient Http
Usage:
var response = await Http.PostAsJsonAsync("todoitems", toitem);
var content = await response.Content.ReadFromJsonAsync<WeatherForecast[]>() ??
Array.Empty();
More details, you could refer to this article.
Upvotes: 1