For another I’m working on I needed a way to run small C# snippets in a web browser, and since I can’t afford fancy compiler severs I turned to WASM to do the job.
I knew about Roslyn (the compiler for C#), and knew of the existence of NuGet packages that should allow for runtime compilation and execution of C# code. So I started with trying to get custom C# code to run on the web.
WASM, and Blazor, seemed like the oblivious choice but I didn’t want to have to
write the entire project in Blazor, ideally I wanted this to be suited as an
npm package. So I began stripping the Blazor WASM example project to see how
much I could get rid of, and as it turns out you can remove almost everything.
The only thing (aside from standard C# boilerplate) that was necessary for
initialized it together.
So the next step was to import that Roslyn package, use it’s built in snippet
executioner (and/or REPL functionality), and all would be done. Except it wasn’t
that easy, because nothing ever is. The built in functions for running snippets
of code relied on having a filesystem where they could find the
compile against, something we can’t have on the web. Eventually after lots of
searching through the internet I found another, although more complicated, way
of doing it. This new way allowed me to download and keep the
.dlls in memory
until they were needed.
If you’re interested in any of this take a look at: the example at
npm package at npmjs.com/package/browser-csharp,
or the source on GitHub.com/89netraM/browser-csharp.