如何从运行时编译的汇编引用动态加载的汇编?

时间:2015-07-13 22:40:49

标签: c# reflection .net-assembly roslyn

我有运行时编译的程序集,它引用位于特定路径中并动态加载的另一个程序集(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();
    }

此处SomeClassDynLoadedAssembly中定义,从dynAssemblyPath动态加载。

如果我将DynLoadedAssembly放入执行程序集文件夹 - 那么它可以正常工作。 其他解决方法是:

但我想动态加载引用的程序集。所以我的问题是:

0 个答案:

没有答案