Understand .NET 9.0 Blazor Hosting Models
Blazor comes in three hosting models: Blazor Server, Blazor WebAssembly (WASM), and Blazor Hybrid. Each model has unique requirements for setup in the Program.cs file and routing. Let's break down what is needed for each.
1. Blazor Server
Blazor Server runs the app on the server, with the UI updates sent to the client over a real-time SignalR connection.
Key Setup in Program.cs
Router
The _Host.cshtml file serves as the entry point. Routes are managed server-side.
Example:
Notable APIs
AddServerSideBlazor(): Adds support for server-side Blazor.MapBlazorHub(): Configures the SignalR endpoint.MapFallbackToPage(): Ensures unmatched routes render the_Host.cshtml.
2. Blazor WebAssembly (WASM)
Blazor WebAssembly runs the app entirely in the browser via WebAssembly, with no dependency on a server for execution.
Key Setup in Program.cs
Router
Routes are resolved client-side because Blazor WASM is fully browser-based.
Example:
Notable APIs
WebAssemblyHostBuilder: Creates the environment for a Blazor WebAssembly app.AddRootComponents(): Mounts the app in the DOM.AddScoped(): Registers a scopedHttpClient.
3. Blazor Hybrid (WebAssembly + Server Interactivity)
Blazor Hybrid combines interactive server rendering and WebAssembly interactivity within the same app. This setup can be used with technologies like .NET MAUI or for apps with advanced rendering needs.
Key Setup in Program.cs
Server-Side Interactive Components
WebAssembly + Server-Side Interactivity
Router
Hybrid apps can combine routing and components across both server and WebAssembly.
Example:
Notable APIs
AddInteractiveServerComponents(): Enables server-side interactive components.AddInteractiveWebAssemblyComponents(): Enables WebAssembly interactivity.AddInteractiveServerRenderMode(): Configures server rendering.AddInteractiveWebAssemblyRenderMode(): Configures WebAssembly rendering.
Differences Between the Hosting Models
| Feature | Blazor Server | Blazor WebAssembly | Blazor Hybrid |
|---|---|---|---|
| Runs On | Server | Browser | Server and Browser |
| State Management | Server-side memory | Client-side (browser) | Mixed |
| Hosting Requirement | SignalR connection | Static file hosting | Depends on scenario |
| Execution | .NET on server | WebAssembly in browser | Both |
| Setup Complexity | Medium | Simple | Advanced |
Key Considerations
Blazor Server:
- Best for apps requiring real-time interactivity and centralized state.
- Relies on a constant connection via SignalR.
Blazor WebAssembly:
- Best for standalone apps that don’t need a backend server for execution.
- Ideal for deploying as static files to a CDN.
Blazor Hybrid:
- Best for advanced scenarios where you need both server-side and client-side rendering.
- Adds complexity but provides flexibility.
Comments
Post a Comment