无法在 .NET(完整)4.5 控制台应用程序中加载 Rosyln 生成的 PCL 程序集

Unable to load Rosyln generated PCL assembly in .NET (Full) 4.5 Console App

我正在尝试使用 Roslyn (Microsoft.CodeAnalysis) 创建一个 PCL 程序集。 我正在引用位于 "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETPortable\v4.5\Profile\Profile259" 的 PCL 程序集。这是我编译实际程序集的代码。

var assemblyName = string.Concat("ODataHQ.SDK.", accountKey, ".dll");
var source = GenerateAccountSource(accountKey, workspace);
var assemblyInfoSource = GetAssemblyInfo(assemblyName);
var assemblyTree = CSharpSyntaxTree.ParseText(assemblyInfoSource);
var tree = CSharpSyntaxTree.ParseText(source);

// Lets add PCL framework assemblies.
var frameworkFiles = new[] {"mscorlib.dll", "Microsoft.CSharp.dll", "System.dll", "System.Core.dll", "System.Runtime.dll"};
var references = frameworkFiles
    .Select(file => Path.Combine(Settings.PCLProfilePath, file))
    .Select(fullPath => MetadataReference.CreateFromFile(fullPath))
    .Cast<MetadataReference>()
    .ToList();

// Lets add third-party dependent assemblies.
references.AddRange(Directory.GetFiles(Settings.SDKDependencyPath, "*.dll")
    .Select(file => MetadataReference.CreateFromFile(file)));

var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var compilation = CSharpCompilation.Create(assemblyName, new [] { assemblyTree, tree }, references, options);

var ms = new MemoryStream();
var result = compilation.Emit(ms);

if (result.Success)
{
    // Reset stream position to read from beginning.
    ms.Position = 0;
    return ms;
}

// Destroy memory stream since it didn't compile successfully.
ms.Dispose();

var firstError = result.Diagnostics
    .Where(d => d.Severity == DiagnosticSeverity.Error)
    .Select(d => d.GetMessage())
    .FirstOrDefault();

throw new CompilationException(firstError);

这是我的 GetAssemblyInfo 方法:

private string GetAssemblyInfo(string assemblyName)
    {
        return @"using System.Reflection;
            using System.Runtime.Versioning;
            [assembly: AssemblyTitle(""" + assemblyName + @""")]
            [assembly: AssemblyVersion(""1.0.*"")]
            [assembly: AssemblyFileVersion(""1.0.*"")]
            [assembly: TargetFramework("".NETPortable,Version=v4.5,Profile=Profile259"", FrameworkDisplayName="".NET Portable Subset"")]";
    }

我将生成的程序集保存到磁盘。然后在另一个控制台应用程序项目中引用它。但是,当我 运行 控制台应用程序并尝试使用动态生成的 PCL 程序集中的类型时,出现以下错误。

'System.IO.FileNotFoundException' 类型的未处理异常发生在 mscorlib.dll 附加信息:无法加载文件或程序集 'ODataHQ.SDK.dvester.dll, Version=1.0.5635.36199, Culture=neutral, PublicKeyToken=null' 或其依赖项之一。系统找不到指定的文件。

谁能帮我找出问题所在?

检查异常的FusionLog 属性(您可能需要在注册表中启用它)。

这会告诉你失败的原因。