Unlock the Power of WebAssembly with Blazor
What is Blazor?
Blazor is an open-source technology that brings .NET development directly to the browser. It comes in two flavors: Blazor Server and Blazor WebAssembly. Both versions are now production-ready.
How Does Blazor Work?
Blazor runs on a version of Xamarin’s Mono framework compiled for Wasm. This allows .NET (C#) applications to run directly in the browser. Blazor compiles .NET code into Wasm, which can then be deployed as a static bundle.
// Example C# code that can be compiled to Wasm
using System;
namespace MyBlazorApp
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
Blazor’s Key Features
- Interoperability with JavaScript libraries: Blazor provides the “IJSRuntime” and “JSRuntime” in C# to directly interact with JavaScript packages alongside your C# code.
- Lifecycle hooks: Blazor has several built-in lifecycle hooks that enable you to control behaviors when the application loads, is destroyed, etc.
- Performance optimization: Blazor has several built-in technologies that improve web application performance and controlling rendering behavior.
Example Application: Vending Machine
To demonstrate the power of Blazor, I created a simple Vending Machine application. This application showcases the basics of Blazor and how to send and retrieve data between client and server.
// Example C# code for the Vending Machine application
using System;
using Microsoft.AspNetCore.Components;
namespace MyVendingMachineApp
{
public class VendingMachineComponent : ComponentBase
{
[Inject]
private IJSRuntime jsRuntime { get; set; }
protected override async Task OnInitializedAsync()
{
// Initialize the vending machine data
await jsRuntime.InvokeVoidAsync("initVendingMachine");
}
}
}
Blazor WebAssembly
The WebAssembly version of the project uses Azure Functions to call locally. In a production-quality version of this application, I would host these on Azure and then get my client app to call the HTTP endpoints from my functions.
Blazor Server
The Blazor Server project is set up similarly to the WebAssembly project, with the exception that I can build out my data (backend) layer within the same project. The Server version uses SignalR for message passing.
Deployment
Both the WebAssembly and Server implementations connect easily with Azure as well as other cloud providers. The WebAssembly implementation also works nicely with static web hosting since the build results in a bundle that can be deployed and read by any browser.
Learn more about Blazor and WebAssembly