如何将 Roslyn 脚本提交用作其他 Roslyn 编译中的程序集

How to use a Roslyn scripting submission as an assembly in other Roslyn compilations

我想在另一个非脚本 Roslyn 编译中重用脚本作为动态程序集,但我终究无法弄清楚如何实现它。

例如,假设我以正常方式创建脚本,然后使用类似以下内容将脚本作为程序集发送到字节流:

var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var compilation = script.GetCompilation().WithOptions(compilationOptions);
using (var ms = new MemoryStream())
{
    EmitResult result = compilation.Emit(ms);
    ms.Seek(0, SeekOrigin.Begin);
    assembly = Assembly.Load(ms.ToArray());
}

现在,假设我想将该程序集提供给另一个非脚本编译作为参考。我不能只使用 assembly,因为 MetadataReference.CreateFrom...() 方法的 none 支持传递实际的 Assembly 实例。作为动态程序集,它没有位置,所以我不能使用 MetadataReference.CreateFromFile().

过去我曾成功地使用 MetadataReference.CreateFromStream() 来处理这类事情,但是当程序集代表脚本提交时这似乎不起作用(我不知道为什么)。编译继续进行,但是一旦您尝试使用提交中的类型,您就会收到如下错误:

System.InvalidCastException: [A]Foo cannot be cast to [B]Foo. Type A originates from 'R*19cecf20-a48e-4a31-9b65-4c0163eba857#1-0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither' in a byte array. Type B originates from 'R*19cecf20-a48e-4a31-9b65-4c0163eba857#1-0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither' in a byte array.

我猜这与评估与加载为字节数组时处于不同上下文中的提交程序集有关。对于在以后的非脚本编译中使用脚本提交中定义的对象和方法的最佳方式,我希望有任何见解或指导。

7 月 29 日更新

我能够得到一个演示问题的最小重现。它可以在 https://github.com/daveaglick/ScriptingAssemblyReuse.

找到

在生成重现时,很明显这个问题的一个重要组成部分是脚本将其中一个 类 的 Type 传递给调用代码,然后调用代码使用 Type 来实例化对象的实例,然后将该实例传递到引用脚本程序集的编译中。当从主机应用程序创建的类型的实例转换为引用编译中的类型时,会发生不匹配。当我重新阅读时,它听起来很混乱,所以希望下面的代码能让它更清楚。

以下是触发此问题的所有代码:

namespace ScriptingAssemblyReuse
{
    public class Globals
    {
        public IFactory Factory { get; set; }    
    }

    public interface IFactory
    {
        object Get();
    }

    public class Factory<T> : IFactory where T : new()
    {
        public object Get() => new T();
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            new Program().Run();
        }

        private Assembly _scriptAssembly;

        public void Run()
        {
            AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;

            // Create the script
            Script<object> script = CSharpScript.Create(@"
                public class Foo { }
                Factory = new ScriptingAssemblyReuse.Factory<Foo>();
                ", ScriptOptions.Default.WithReferences(MetadataReference.CreateFromFile(typeof(IFactory).Assembly.Location)), typeof(Globals));

            // Create a compilation and get the dynamic assembly
            CSharpCompilationOptions scriptCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            Compilation scriptCompilation = script.GetCompilation().WithOptions(scriptCompilationOptions);
            byte[] scriptAssemblyBytes;
            using (MemoryStream ms = new MemoryStream())
            {
                EmitResult result = scriptCompilation.Emit(ms);
                ms.Seek(0, SeekOrigin.Begin);
                scriptAssemblyBytes = ms.ToArray();
            }
            _scriptAssembly = Assembly.Load(scriptAssemblyBytes);

            // Evaluate the script
            Globals globals = new Globals();
            script.RunAsync(globals).Wait();

            // Create the consuming compilation
            string assemblyName = Path.GetRandomFileName();
            CSharpParseOptions parseOptions = new CSharpParseOptions();
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
                public class Bar
                {
                    public void Baz(object obj)
                    {
                        Script.Foo foo = (Script.Foo)obj;  // This is the line that triggers the exception 
                    }
                }", parseOptions, assemblyName);
            CSharpCompilationOptions compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            string assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);
            CSharpCompilation compilation = CSharpCompilation.Create(assemblyName, new[] {syntaxTree},
                new[]
                {
                    MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")),
                    MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.dll")),
                    MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")),
                    MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll"))
                }, compilationOptions);
            using (MemoryStream ms = new MemoryStream(scriptAssemblyBytes))
            {
                compilation = compilation.AddReferences(MetadataReference.CreateFromStream(ms));
            }

            // Get the consuming assembly
            Assembly assembly;
            using (MemoryStream ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);
                ms.Seek(0, SeekOrigin.Begin);
                byte[] assemblyBytes = ms.ToArray();
                assembly = Assembly.Load(assemblyBytes);
            }

            // Call the consuming assembly
            Type barType = assembly.GetExportedTypes().First(t => t.Name.StartsWith("Bar", StringComparison.Ordinal));
            MethodInfo bazMethod = barType.GetMethod("Baz");
            object bar = Activator.CreateInstance(barType);
            object obj = globals.Factory.Get();
            bazMethod.Invoke(bar, new []{ obj });  // The exception bubbles up and gets thrown here
        }

        private Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
        {
            if (_scriptAssembly != null && args.Name == _scriptAssembly.FullName)
            {
                // Return the dynamically compiled script assembly if given it's name
                return _scriptAssembly;
            }
            return null;
        }
    }
}

我想我已经解开了谜团。这是发生了什么:

  • 创建脚本。
  • 获取脚本的编译,但覆盖编译选项。具体来说,它使用默认值 ScriptClassName,即 Script 而不是脚本生成的 API(例如 Submission#0)- 这就是症结所在事情.
  • 使用覆盖的选项发出程序集并将其从流中加载到内存中。
  • 运行 脚本。此时有两个不同的和不兼容的同名程序集被加载到AppDomain使用字节数组。
  • 将流作为元数据引用添加到新的编译中并在代码中使用它。它编译得很好,因为它使用的是从重写选项生成的程序集。您将无法使用脚本创建的实际程序集编译它,因为 Submission#0 这样的名称在 C# 中是非法的。如果不是,那么您可以将实际脚本 Assembly 实例放入全局变量中并在 OnAssemblyResolve.
  • 中使用它
  • 使用 Submission#0+Foo 类型的参数调用方法 Baz 并尝试将其转换为 Script+Foo

总而言之 - 我认为使用当前的 Roslyn 脚本无法做到这一点 API。但是,这些 API 并不是编译脚本的唯一方法。您可以自己创建一个编译并将 SourceCodeKind 设置为 Script。你必须自己做很多事情,比如 运行 主脚本方法、处理全局变量等。我做了这样的事情 in RoslynPad 因为我希望脚本程序集与 PDB 一起加载(所以异常会有行信息)。