首页 > 解决方案 > PowerShell 7.0.x 无法加载文件或程序集 Microsoft.CodeAnalysis

问题描述

我有一个 .NET Core 3.1 类库,它使用一个名为RazorEngineCore的 nuget 包,它引用Microsoft.CodeAnalysis.CSharp v3.7.0,然后当我在 .NET Core Exe 或 PowerShell 7.1 中使用它时引用Microsoft.CodeAnalysis.Common v3.7.0它可以正常工作,但是当我使用 PowerShell 7.0.x 时,我收到以下错误消息:

System.IO.FileLoadException: Could not load file or assembly 'Microsoft.CodeAnalysis, Version=3.7.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.   at System.Runtime.Loader.AssemblyLoadContext.LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, String ilPath, String niPath, ObjectHandleOnStack retAssembly)   at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)   at System.Reflection.Assembly.LoadFrom(String assemblyFile)   at System.Reflection.Assembly.LoadFromResolveHandler(Object sender, ResolveEventArgs args)   at System.Runtime.Loader.AssemblyLoadContext.InvokeResolveEvent(ResolveEventHandler eventHandler, RuntimeAssembly assembly, String name)   at System.Runtime.Loader.AssemblyLoadContext.OnAssemblyResolve(RuntimeAssembly assembly, String assemblyFullName)

我启用了融合日志记录,没有输出,内部异常没有提供对任何丢失 dll 的引用。我正在调用的 powershell 代码是这样的:

    Add-Type -Path "$($PSScriptRoot)\ComponentHealth.Rendering.dll"

    $ViewModel = [PSCustomObject]@{
        Name     = 'Kevin'
    }

    $template = "Hello @Model.Name"

    try {
        $output = [ComponentHealth.Rendering.Rendering]::Render("Bob", $template, $ViewModel) 
    } catch {
        $ex = $_.Exception
        $base = $_.Exception.GetBaseException()
        Write-Host $ex
    }
    Write-Host $output 

我不明白为什么这在 exe 应用程序或 PowerShell 7.1.x 中有效,但在 PowerShell 7.0.x 中无效。不幸的是,我不能使用不同版本的 PowerShell,因为这需要添加到固定在 PowerShell 运行时 7.0.3 的 Azure App Function 中。

标签: c#.netpowershellazure-function-apppowershell-7.0

解决方案


我们发现了这个问题,如果您尝试导入的 dll 版本高于 PowerShell Core 运行时附带的版本,您将在尝试加载 dll 时遇到异常。我们通过使用低于 PowerShell 7.0.3 随附版本的 Microsoft.CodeAnalysis.CSharp重新编译RazorEngineCore包来解决此问题,现在一切正常。


推荐阅读