我有运行时编译的程序集,它引用位于特定路径中并动态加载的另一个程序集(DynLoadedAssembly)。当我执行运行时编译的程序集时,出现错误:System.IO.FileNotFoundException Could not load file or assembly 'DynLoadedAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies
。
查看代码:
public string Run()
{
var text = @"
using DynLoadedAssembly;
public class DynClass
{
public static string Evaluate()
{
return new SomeClass().Do();
}
}";
var dynAssemblyPath = @"c:\path\to\DynLoadedAssembly.dll";
Assembly.LoadFile(dynAssemblyPath);
var tree = SyntaxFactory.ParseSyntaxTree(text);
var compilation = CSharpCompilation.Create(
"calc",
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
syntaxTrees: new[] { tree },
references: new[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(dynAssemblyPath)
}
);
Assembly compiledAssembly;
using (var stream = new MemoryStream())
{
var compileResult = compilation.Emit(stream);
compiledAssembly = Assembly.Load(stream.GetBuffer());
}
Type dynClass = compiledAssembly.GetType("DynClass");
MethodInfo evaluate = dynClass.GetMethod("Evaluate");
return evaluate.Invoke(null, null).ToString();
}
此处SomeClass
在DynLoadedAssembly
中定义,从dynAssemblyPath动态加载。
如果我将DynLoadedAssembly
放入执行程序集文件夹 - 那么它可以正常工作。
其他解决方法是:
AssemblyResolve
事件处理程序但我想动态加载引用的程序集。所以我的问题是:
DynLoadedAssembly
库?