Required Assembly For an MSBuild Task Cannot Be Loaded

Viewed 513

I am trying to run a simple task after build in a .NET Core console app.

Here is my 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>

And here is the task 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; }
    }
}

But I am getting the following error:

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.

I could not figure out what the problem is.

1 Answers

The bin folder from which you're loading your Task dll doesn't have all the dlls needed to actually run the assemblies there, as it's expected that they will be loaded with certain runtime dlls supplied from elsewhere. MSBuild doesn't appear to be finding those ambiently-available dlls (it depends on the loading behaviour of the specific loader).

Try adding the following to the csproj, which will splurge all possible assemblies for MSBuild to find:

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

Publishing rather than just building the project supplying the Task should achieve the same.

(the above is guesswork but it's worth a go)

P.S. I'd recommend supplying the task from a project other than the one consuming it - you've got yourself into a chicken-and-egg kind of situation here

Related