无法加载 MSBuild 任务所需的程序集

Required Assembly For an MSBuild Task Cannot Be Loaded

我正在尝试 运行 在构建 .NET Core 控制台应用程序后执行一个简单的任务。

这是我的 cspoj:

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp3.1</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Microsoft.Build.Utilities.Core" Version="16.8.0" />
    </ItemGroup>


    <UsingTask TaskName="SimpleTask" AssemblyFile = "bin\Debug\netcoreapp3.1\ConsoleApp10.dll">

    </UsingTask>

    <Target Name="MyTarget" AfterTargets="Build">
        <SimpleTask/>
    </Target>

</Project>

这是任务 class:

using Microsoft.Build.Utilities;


namespace ConsoleApp10.MyTasks
{
    public class SimpleTask : Task
    {
        public override bool Execute()
        {
            Log.LogWarning("warning message");
            return true;
        }

        public string MyProperty { get; set; }
    }
}

但我收到以下错误:

Error   MSB4018 The "SimpleTask" task failed unexpectedly.
System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at ConsoleApp10.MyTasks.SimpleTask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext()

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.

我不知道是什么问题。

您从中加载任务 dll 的 bin 文件夹没有实际 运行 那里的程序集所需的所有 dll,因为预计它们将加载某些 运行从其他地方提供的时间 dll。 MSBuild 似乎没有找到那些环境可用的 dll(这取决于特定加载程序的加载行为)。

尝试将以下内容添加到 csproj,这将为 MSBuild 寻找所有可能的程序集:

<PropertyGroup>
    <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>

发布而不是仅仅构建提供任务的项目应该达到同样的效果。

(以上是猜测,但值得一试)

P.S。我建议从一个项目而不是消耗它的项目提供任务 - 你在这里陷入了鸡和蛋的情况