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

本文关键字:Rosyln 加载 程序集 PCL 应用程序 控制台 net Full | 更新日期: 2023-09-27 17:54:03

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

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类型异常。在mscorlib.dll中发生FileNotFoundException'其他信息:无法加载文件或程序集"ODataHQ.SDK.dvester.dll, Version=1.0.5635.36199,区域性=中性,PublicKeyToken=null"或其依赖项之一。系统找不到指定的文件

谁能帮我弄清楚出了什么问题?

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

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