c# - 无法在 asp.net core 3.1 中添加对 CSharpCompilation 的 MetadataReference 的引用
问题描述
我想创建运行时类,但是当使用来自 Stimulsoft.Report.Dictionary 的属性 [StiAlias("id")]; 发送错误:
[0] = (1,101):错误 CS0012:“属性”类型是在未引用的程序集中定义的。您必须添加对程序集“netstandard,Version=2.1.0.0,Culture=neutral,PublicKeyToken=cc7b13ffcd2ddd51”的引用。
public object CreateClassRunTime()
{
string strClass =
@"using System; " +
//"using System.Collections.Generic;" +
"using Stimulsoft.Report.Dictionary;" +
"namespace VModel { public class AddressViewTest { " +
"[StiAlias(\"id\")]" +
"public int id { get; set; }" +
" public int? updUser { get; set; } } }";
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(strClass);
string assemblyName = Path.GetRandomFileName();
var refPaths = new[] {
typeof(object).Assembly.Location,
typeof(System.ComponentModel.DataAnnotations.DisplayAttribute).Assembly.Location,
typeof(System.Runtime.AssemblyTargetedPatchBandAttribute).Assembly.Location,
typeof(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo).Assembly.Location,
typeof(Stimulsoft.Report.Dictionary.StiAliasAttribute).GetTypeInfo().Assembly.Location,
};
MetadataReference[] references = refPaths.Select(r => MetadataReference.CreateFromFile(r)).ToArray();
CSharpCompilation compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
object instance = null;
try
{
byte[] image = null;
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
Console.Write(result.Diagnostics.First().GetMessage());
}
image = ms.ToArray();
//Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms);
//instance = assembly.CreateInstance("VModel.AddressViewTest");
}
Assembly assembly = null;
using (var stream = new MemoryStream(image))
assembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(stream);
//var type = assembly.GetType("VModel.AddressViewTest");
instance = assembly.CreateInstance("VModel.AddressViewTest");
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
return instance;
}
由广告解决错误:
var ns = Assembly.Load("netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51");
和广告参考:
var refPaths = new[] {
ns.Location,
typeof(object).Assembly.Location,...
}
解决方案
通过添加解决了错误:
var ns = Assembly.Load("netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51");
和广告参考:
var refPaths = new[] {
ns.Location,
typeof(object).Assembly.Location,...}
推荐阅读
- c# - EF Core 3.1 在迁移中没有返回正确的错误
- ocaml - 返回 OCAML 中参数的更改值
- angular - 将 Angular 应用程序的功能分支部署到 GitHub Pages 的正确方法是什么?
- azure - 使用“大于”运算符实现外部联接
- python - 在函数调用之间未重新分配 Set
- python - 我的登录表单不起作用,它说在分配之前引用了变量
- python - 更改了 Django 3.2 中的导入结构?
- android - 是否可以指定重量和最小高度?
- python - 使用 summary_col 时的回归输出
- mysql - 无法从 MySQL 中的标题列创建外键