ameya
ameya

Reputation: 1668

Distribute custom MS Build Task with .NET Standard and VS 2017 via Nuget

I have a .NET Standard library (1.4) VS 2017 project that contains custom MS Build task (MyTask) that need to be distributed via Nuget package (Let's say MyCustomTask.dll and it contains MyTask and Portable.targets that will be imported by target project)

This Nuget package with custom build task is then used by target .NET Standard (1.4) project cspro file to import the Portable.targets that invoke the Custom Build task.

However, at this point I keep on getting the build error Could not load file or assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.

I tried .NET Standard (1.4, 1.5 and 1.6) but same error.

Upvotes: 2

Views: 1290

Answers (1)

Martin Ullrich
Martin Ullrich

Reputation: 100811

The problem is that the consuming application, MSBuild.exe in this case, would need to include all the forwarding assemblies necessary to run netstandard tasks (e.g. depend on the NETStandard.Library).

The best solution in this case is multi-targeting the task library to a .net framework and a .net standard target framework:

<TargetFrameworks>netstandard1.6;net46</TargetFrameworks>

The idea is to have 2 dlls that will contain the task. In the project files contained in the NuGet package instead of using a dll path directly in <UsingTask>, the idea is to using a different dll file based on the $(MSBuildRuntimeType) property, which will be Core on the .NET Core version of MSBuild:

<PropertyGroup>
  <_CustomTaskAssemblyTFM Condition="'$(MSBuildRuntimeType)' == 'Core'">netstandard1.6</_CustomTaskAssemblyTFM>
  <_CustomTaskAssemblyTFM Condition="'$(MSBuildRuntimeType)' != 'Core'">net46</_CustomTaskAssemblyTFM>
  <_CustomTaskAssembly>$(MSBuildThisFileDirectory)..\tools\$(_CustomTaskAssemblyTFM)\CustomTaskAssemblyName.dll</_CustomTaskAssembly>
</PropertyGroup>

<UsingTask TaskName="SomeCustomTask" AssemblyFile="$(_CustomTaskAssembly)" />

You can see examples of this in the asp.net core build tools and the .NET Core SDK.

Upvotes: 5

Related Questions