Lesson 32 of 40
Advanced Topics
Expert
45 min
WebAssembly with WASI
Compile .NET applications to WASI WebAssembly for portable, sandboxed execution outside the browser on servers, edge nodes, and IoT.
Part 1: WASI Overview
WASI (WebAssembly System Interface) lets .NET run as WASM outside browsers. Use cases:
- Serverless functions on Fastly/Cloudflare Workers
- Plugin systems with sandboxed execution
- Portable CLI tools
- Edge computing
Part 2: Publishing to WASI
<!-- .csproj -->
<RuntimeIdentifier>wasi-wasm</RuntimeIdentifier>
<PublishSingleFile>true</PublishSingleFile>
# Publish
dotnet publish -c Release
# Run with wasmtime:
wasmtime ./bin/Release/wasi-wasm/MyApp.wasm
<RuntimeIdentifier>wasi-wasm</RuntimeIdentifier>
<PublishSingleFile>true</PublishSingleFile>
# Publish
dotnet publish -c Release
# Run with wasmtime:
wasmtime ./bin/Release/wasi-wasm/MyApp.wasm
Part 3: Component Model
The WASM Component Model enables type-safe interop between languages. Define interfaces in WIT (WebAssembly Interface Types):
// orders.wit
interface orders {
record order { id: u32, total: f64 }
get-order: func(id: u32) -> order;
}
interface orders {
record order { id: u32, total: f64 }
get-order: func(id: u32) -> order;
}
Part 4: Wasmtime in .NET Host
var engine = new Engine();
var module = Module.FromFile(engine, "plugin.wasm");
var store = new Store(engine);
var instance = Instance.NewStore(store, module);
// Call exported WASM function safely from .NET
var module = Module.FromFile(engine, "plugin.wasm");
var store = new Store(engine);
var instance = Instance.NewStore(store, module);
// Call exported WASM function safely from .NET