【发布时间】:2019-06-13 19:51:54
【问题描述】:
在 Blazor 应用程序中,我想加载一个外部程序集并执行一个方法。为此,我使用 Blazor 模板创建了一个新的 ASP.Net Core Web 应用程序。
然后,在 Razor 页面(将由浏览器/wasm 编译和执行)中,我使用反射来加载程序集并运行方法(基于代码 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);
方法WriteSomething 包含一个Console.WriteLine(),它在浏览器的控制台中打印一些东西,这要感谢 blazor/mono.wasm 的优点。这个库中的完整代码是:
namespace MyCustomLib
{
public class MyCustomClass
{
public void WriteSomething()
{
System.Console.WriteLine("This is printed from a loaded dll 3 !");
}
}
}
结果:
如您所见,当 MyCustomLib.dll 构建为 .NET Framework 类库时,这非常有用。但是,我想使用 .NET Standard 类库。
当我将 MyCustomLib.dll 构建为 .NET Standard 2.0 库并执行相同的 blazor 应用程序时,我在浏览器的控制台中收到以下错误:
无法加载文件或程序集 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' 或其依赖项之一。
我希望 mono.wasm 会加载必要的依赖项来支持 .NET Standard 程序集。
- 将程序集加载到 AppDomain 会产生相同的结果。
var assembly = AppDomain.CurrentDomain.Load(bytes);
切换到 netstandard 1.6 给了我一个类似的错误,这次是关于
System.Runtime(因为我假设 mono.wasm 期望Mono.Runtime)。也许有一种方法可以对 netstandard2.0 包引用的程序集执行
LoadAssembly,但我不知道如何。
如何使用 Blazor 将 .NET Standard 2.0 加载到浏览器环境中?
【问题讨论】:
标签: c# asp.net-core .net-standard webassembly blazor