lundi 13 juillet 2015

How to reference dynamically loaded assembly from runtime compiled assembly?

I have runtime-compiled assembly that references another assembly (DynLoadedAssembly) that is located in specific path and loaded dynamically. When I execute runtime-compiled assembly, I get an error: 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:\!\norbit\tmp\Roslyn\ConsoleApplication1\DynLoadedAssembly\bin\Debug\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();
    }

If I place DynLoadedAssembly into execution assembly folder - then is works fine. Other workarounds is:

But I want to load referenced assembly dynamically. So my questions are:

  • Why "Step 2: Checking for Previously Referenced Assemblies" (http://ift.tt/1Jerkhw) failed?
  • How to make my compiled assembly find previosly loaded assembly in current domain?




Aucun commentaire:

Enregistrer un commentaire