How to create a .NET Core library that is Multi-Targeting but targets different dll's per framework?

949 Views Asked by At

I'm trying to update a library that is currently targeting .NET4.0 to:

  • NETStandard 2.0
  • NET4.5.2

using Multi-Targeting.

The dependent library I'm using is Microsoft.Build.Framework. It's found either in two places:

  • NuGet and min level is NET4.6
  • GAC via Full Framework (e.g. C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\Microsoft.Build.Framework.dll)

Because the nuget package min level is above 4.5.2, I can't use that nuget package in the 452 target.

So, is it possible to say: - When using NS20, please use the nuget package. - When using NET4.5.2, please use the GAC version.

thanks!

2

There are 2 best solutions below

0
On BEST ANSWER

You can define your dependencies conditionally, depending on what current target framework the project is being built on. For that, you would adjust your project file to use the NuGet dependencies in one case, or standard non-NuGet references in the other case.

That would look like this:

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

  <PropertyGroup>
    <!-- other properties -->
    <TargetFrameworks>netstandard2.0;net452</TargetFrameworks>
  </PropertyGroup>

  <ItemGroup>
    <!-- common references -->
  </ItemGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'net452'">
     <Reference Include="Microsoft.Build.Framework" />
  </ItemGroup>
  <ItemGroup Condition="'$(TargetFramework)' != 'net452'">
     <PackageReference Include="Microsoft.Build.Framework" Version="15.7.179" />
  </ItemGroup>

</Project>

So net452 would get the normal assembly reference Microsoft.Build.Framework with the Reference element, which can be resolved from the GAC or the local directory, and other frameworks will resolve it from NuGet using a PackageReference.

0
On

The trick is modify your csproj and specify manually the packages to use under either specific framework.

So here's what I ended up doing. Take note of:

  • PackageReference: get this from NuGet.
  • Reference: get this from your GAC.

.

<PropertyGroup>
  <TargetFrameworks>netstandard2.0;net452</TargetFrameworks>
</PropertyGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
  <PackageReference Include="Microsoft.Build.Framework" Version="15.7.179" />
  <PackageReference Include="Microsoft.Build.Utilities.Core" Version="15.7.179" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'net452' ">
  <Reference Include="Microsoft.Build.Framework" Version="15.7.179" />
  <Reference Include="Microsoft.Build.Utilities.v4.0" Version="15.7.179" />
</ItemGroup>

So here, we are getting the packages from NuGet if the framework is NS20 while we try and get them from the GAC if it's for NET452.

Winner winner, chicken dinner!