In a Blazor app, I want to load an external assembly and execute a method. For this, I have created a new ASP.Net Core webapplication using the Blazor template.
Then, in a Razor Page (which will be compiled and executed by browser/wasm) I use reflection to load the assembly and run the method (based on code found here)
// download external assembly from server
HttpClient client = new HttpClient();
var bytes = await client.GetByteArrayAsync("http://localhost:62633/_framework/MyCustomLib.dll");
//load assembly
var assembly = System.Reflection.Assembly.Load(bytes);
// get type/method info
var type = assembly.GetType("MyCustomLib.MyCustomClass");
var method = type.GetMethod("WriteSomething");
// instantiate object and run method
object classInstance = Activator.CreateInstance(type, null);
method.Invoke(classInstance, null);
The method WriteSomething
contains a single Console.WriteLine()
which prints something in the browser's console, thanks to blazor/mono.wasm goodness. The complete code in this library is:
namespace MyCustomLib
{
public class MyCustomClass
{
public void WriteSomething()
{
System.Console.WriteLine("This is printed from a loaded dll 3 !");
}
}
}
Result:
As you can see, this works great when MyCustomLib.dll is built as a .NET Framework Class Library. However, I want to use a .NET Standard Class Library.
When I build a MyCustomLib.dll
as a .NET Standard 2.0 library, and execute the same blazor app, I get the following error in the browser's console:
Could not load file or assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies.
I would expect mono.wasm would have loaded the necessary dependencies to support .NET Standard assemblies.
- Loading the assembly into the AppDomain yields the same result.
var assembly = AppDomain.CurrentDomain.Load(bytes);
Switching down to netstandard 1.6 gives me a similar error, this time about
System.Runtime
(because mono.wasm expectsMono.Runtime
I assume).Maybe there's a way to perform
LoadAssembly
on the assemblies referenced by the netstandard2.0 package, but I wouldn't know how.
How can I load a .NET Standard 2.0 into the browser environment using Blazor?