C# Roslyn 编译 - 在动态编译的代码中使用 Nuget 包 - 编译但在运行时抛出异常(无法加载文件或程序集)

标签 c# .net nuget roslyn roslyn-code-analysis

我尝试使用 Roslyn 编译器在动态编译代码中使用 Nuget 包。

我想在我的代码中使用 Nuget 包(在我的示例中 https://www.nuget.org/packages/TinyCsvParser/ )。所以我下载了这个包并将其解压到一个文件夹(C:\Data\packages\tinycsvparser.2.6.1)

但我不希望它成为我的应用程序的直接依赖项。因此项目本身没有引用它,我不想将其复制到 bin/Debug-Folder 中。

Nuget-Package-DLL 应该可以位于我的硬盘上的任何位置。

编译运行没有任何错误。但在运行时,在 method.Invoke(fooInstance, null) 行上,我得到以下异常:

Could not load file or assembly 'TinyCsvParser, Version=2.6.1.0, Culture=neutral, PublicKeyToken=d7df35b038077099' or one of its dependencies. The system cannot find the file specified.

我如何告诉程序应该在哪里寻找 DLL? 我用下面的行尝试了

Assembly nugetAssembly = Assembly.LoadFrom(pathToNugetDLL);

但这并没有帮助。

感谢您就如何解决此问题提供任何建议。

这是我的代码(原型(prototype)):

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Text;

namespace Playground
{
   public static class Program
   {
      private const string pathToNugetDLL = @"C:\Data\packages\tinycsvparser.2.6.1\lib\net45\TinyCsvParser.dll";

      private const string firstClass =
@"
using TinyCsvParser;

namespace A
{
    public class MyClass
    {
        public int MyFunction()
         {
            CsvParserOptions csvParserOptions = new CsvParserOptions(true, ';');
            return 1;
         }
    }
}";

      public static void Main()
      {
         CSharpParseOptions parseOptions = new CSharpParseOptions(LanguageVersion.CSharp7, DocumentationMode.Parse, SourceCodeKind.Regular);
         SyntaxTree parsedSyntaxTree = SyntaxFactory.ParseSyntaxTree(firstClass, parseOptions);

         List<string> defaultNamespaces = new List<string>() { };

         //// Referenzen über Kommentare heraussuchen:
         List<MetadataReference> defaultReferences = CreateMetadataReferences();

         var encoding = Encoding.UTF8;

         var assemblyName = Path.GetRandomFileName();
         var symbolsName = Path.ChangeExtension(assemblyName, "pdb");
         var sourceCodePath = "generated.cs";

         var buffer = encoding.GetBytes(firstClass);
         var sourceText = SourceText.From(buffer, buffer.Length, encoding, canBeEmbedded: true);

         var syntaxTree = CSharpSyntaxTree.ParseText(
             sourceText,
             new CSharpParseOptions(),
             path: sourceCodePath);

         var syntaxRootNode = syntaxTree.GetRoot() as CSharpSyntaxNode;
         var encoded = CSharpSyntaxTree.Create(syntaxRootNode, null, sourceCodePath, encoding);


         CSharpCompilationOptions defaultCompilationOptions =
               new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                       .WithOverflowChecks(true).WithOptimizationLevel(OptimizationLevel.Debug).WithPlatform(Platform.AnyCpu)
                       .WithUsings(defaultNamespaces);

         CSharpCompilation compilation = CSharpCompilation.Create(
             assemblyName,
             syntaxTrees: new[] { encoded },
             references: defaultReferences,

             options: defaultCompilationOptions
         );

         using (var assemblyStream = new MemoryStream())
         using (var symbolsStream = new MemoryStream())
         {
            var emitOptions = new EmitOptions(
                    debugInformationFormat: DebugInformationFormat.Pdb,
                    pdbFilePath: symbolsName);

            var embeddedTexts = new List<EmbeddedText> { EmbeddedText.FromSource(sourceCodePath, sourceText) };

            EmitResult result = compilation.Emit(
                peStream: assemblyStream,
                pdbStream: symbolsStream,
                embeddedTexts: embeddedTexts,
                options: emitOptions);


            if (result.Success)
            {
               Console.WriteLine("Complation succeeded!");
               try
               {
                  Assembly nugetAssembly = Assembly.LoadFrom(pathToNugetDLL);

                  var assembly = Assembly.Load(assemblyStream.ToArray(), symbolsStream.ToArray());
                  var type = assembly.GetType("A.MyClass");

                  MethodInfo method = type.GetMethod("MyFunction");

                  var fooInstance = Activator.CreateInstance(type);
                  method.Invoke(fooInstance, null);
                  
               }
               catch (Exception ex)
               {
                  int i = 0;
               }
            }
         }
      }
      private static List<MetadataReference> CreateMetadataReferences()
      {
         string defaultPath = typeof(object).Assembly.Location.Replace("mscorlib", "{0}");

         var metadatenReferences = new List<MetadataReference>()
            {
                MetadataReference.CreateFromFile(string.Format(defaultPath, "mscorlib")),
                MetadataReference.CreateFromFile(string.Format(defaultPath, "System")),
                MetadataReference.CreateFromFile(string.Format(defaultPath, "System.Data")),
                MetadataReference.CreateFromFile(string.Format(defaultPath, "System.Core")),
                MetadataReference.CreateFromFile(string.Format(defaultPath, "System.ComponentModel.DataAnnotations")),
                MetadataReference.CreateFromFile(string.Format(defaultPath, "System.Xml")),
                MetadataReference.CreateFromFile(string.Format(defaultPath, "netstandard")),
            };

         string strExtraDll = pathToNugetDLL;
         metadatenReferences.Add(MetadataReference.CreateFromFile(strExtraDll));

         return metadatenReferences;
      }
   }
         
}

最佳答案

我可以通过使用事件处理程序解决问题

AppDomain.CurrentDomain.AssemblyResolve

有了它我可以解决依赖关系。

这里是原型(prototype)代码的最终结果:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

namespace Playground
{
   public static class Program
   {

      public static void Main()
      {
         var test = new Test();
         test.TestMethod();
      }
   }
   public class Test

   {

      private const string pathToNugetDLL = @"C:\Data\packages\tinycsvparser.2.6.1\lib\net45\TinyCsvParser.dll";

      private const string firstClass =
@"
using TinyCsvParser;

namespace A
{
    public class MyClass
    {
        public int MyFunction()
         {
            CsvParserOptions csvParserOptions = new CsvParserOptions(true, ';');
            return 1;
         }
    }
}";


      public void TestMethod()
      {
         CSharpParseOptions parseOptions = new CSharpParseOptions(LanguageVersion.CSharp7, DocumentationMode.Parse, SourceCodeKind.Regular);
         SyntaxTree parsedSyntaxTree = SyntaxFactory.ParseSyntaxTree(firstClass, parseOptions);

         List<string> defaultNamespaces = new List<string>() { };

         //// Referenzen über Kommentare heraussuchen:
         List<MetadataReference> defaultReferences = CreateMetadataReferences();

         var encoding = Encoding.UTF8;

         var assemblyName = Path.GetRandomFileName();
         var symbolsName = Path.ChangeExtension(assemblyName, "pdb");
         var sourceCodePath = "generated.cs";

         var buffer = encoding.GetBytes(firstClass);
         var sourceText = SourceText.From(buffer, buffer.Length, encoding, canBeEmbedded: true);

         var syntaxTree = CSharpSyntaxTree.ParseText(
             sourceText,
             new CSharpParseOptions(),
             path: sourceCodePath);

         var syntaxRootNode = syntaxTree.GetRoot() as CSharpSyntaxNode;
         var encoded = CSharpSyntaxTree.Create(syntaxRootNode, null, sourceCodePath, encoding);


         CSharpCompilationOptions defaultCompilationOptions =
               new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                       .WithOverflowChecks(true).WithOptimizationLevel(OptimizationLevel.Debug).WithPlatform(Platform.AnyCpu)
                       .WithUsings(defaultNamespaces);

         CSharpCompilation compilation = CSharpCompilation.Create(
             assemblyName,
             syntaxTrees: new[] { encoded },
             references: defaultReferences,

             options: defaultCompilationOptions
         );

         using (var assemblyStream = new MemoryStream())
         using (var symbolsStream = new MemoryStream())
         {
            var emitOptions = new EmitOptions(
                    debugInformationFormat: DebugInformationFormat.Pdb,
                    pdbFilePath: symbolsName);

            var embeddedTexts = new List<EmbeddedText> { EmbeddedText.FromSource(sourceCodePath, sourceText) };

            EmitResult result = compilation.Emit(
                peStream: assemblyStream,
                pdbStream: symbolsStream,
                embeddedTexts: embeddedTexts,
                options: emitOptions);


            if (result.Success)
            {
               Console.WriteLine("Complation succeeded!");
               try
               {
                  AppDomain.CurrentDomain.AssemblyResolve += AppDomain_AssemblyResolve;

                  Assembly nugetAssembly = Assembly.LoadFrom(pathToNugetDLL);

                  var assembly = Assembly.Load(assemblyStream.ToArray(), symbolsStream.ToArray());
                  var type = assembly.GetType("A.MyClass");

                  MethodInfo method = type.GetMethod("MyFunction");

                  var fooInstance = Activator.CreateInstance(type);
                  method.Invoke(fooInstance, null);

               }
               catch (Exception ex)
               {
                  int i = 0;
               }
               finally
               {
                  AppDomain.CurrentDomain.AssemblyResolve -= AppDomain_AssemblyResolve;
               }
            }
         }
      }


      private Assembly AppDomain_AssemblyResolve(object sender, ResolveEventArgs args)
      {
         string[] assemblyInfoSplitted = args.Name.Split(',');
         string strSearchedForAssemblyName = assemblyInfoSplitted[0];

         var fileInfo = new FileInfo(pathToNugetDLL);
         var strAssemblyName = Regex.Replace(fileInfo.Name, ".dll", "", RegexOptions.IgnoreCase);
         if (strSearchedForAssemblyName.ToLower() == strAssemblyName.ToLower())
         {
            //File.ReadAllBytes because DLL might be deleted afterwards in the filesystem
            return Assembly.Load(File.ReadAllBytes(pathToNugetDLL));
         }

         throw new Exception($"Could not resolve Assembly '{strSearchedForAssemblyName}'.");
      }

      private static List<MetadataReference> CreateMetadataReferences()
      {
         string defaultPath = typeof(object).Assembly.Location.Replace("mscorlib", "{0}");

         var metadatenReferences = new List<MetadataReference>()
            {
                MetadataReference.CreateFromFile(string.Format(defaultPath, "mscorlib")),
                MetadataReference.CreateFromFile(string.Format(defaultPath, "System")),
                MetadataReference.CreateFromFile(string.Format(defaultPath, "System.Data")),
                MetadataReference.CreateFromFile(string.Format(defaultPath, "System.Core")),
                MetadataReference.CreateFromFile(string.Format(defaultPath, "System.ComponentModel.DataAnnotations")),
                MetadataReference.CreateFromFile(string.Format(defaultPath, "System.Xml")),
                MetadataReference.CreateFromFile(string.Format(defaultPath, "netstandard")),
            };

         string strExtraDll = pathToNugetDLL;
         metadatenReferences.Add(MetadataReference.CreateFromFile(strExtraDll));

         return metadatenReferences;
      }
   }

}

关于C# Roslyn 编译 - 在动态编译的代码中使用 Nuget 包 - 编译但在运行时抛出异常(无法加载文件或程序集),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68395574/

相关文章:

c# - ELMAH 不从本地主机发送电子邮件

c# 允许变量调用的多行字符串

.net - 在 Web API 中获取 Microsoft.AspNet.WebApi.Cors 版本问题

c# - 缺少的文件是packages\Microsoft.Net.Compilers.2.4.0\build\Microsoft.Net.Compilers.props

.net - 更新解决方案中所有项目中的 nuget 包

c# - 派生类和基类,我可以显式设置基类吗?

c# - WebRequest:查询字符串数据与 x-www-form-urlencoded 内容

c# - 使用 ASP.NET Core Entity Framework 在数据层中进行数据加密

.net - 将 Dictionary<string,string> 转换为数组

visual-studio-2013 - Visual Studio 2013 不会以管理员身份运行