How to target multiple frameworks in .NET Core

Hello 😉,

It's possible to build for multiple frameworks in .NET Core without the Visual Studio IDE, and it's not difficult.

Here's how:

  • Within your .csproj project file, find the <PropertyGroup> element and replace <TargetFramework> with <TargetFrameworks>
<PropertyGroup>  
 <TargetFrameworks>netcoreapp1.1;net46;net452</TargetFrameworks>
</PropertyGroup>  
  • Here, we are targeting the following frameworks
    • .NET Core 1.1
    • .NET Framework 4.6
    • .NET Framework 4.5.2
  • Be sure to separate the frameworks you intend to target with a semicolon ;
  • Add an <ItemGroup> element within the global <Project> element with an appropriate Condition attribute for each framework you intent to target such as:
<ItemGroup Condition="'$(TargetFramework)' == 'net46'">  
    <Reference Include="Microsoft.CSharp" />
</ItemGroup>  
<ItemGroup Condition="'$(TargetFramework)' == 'net452'">  
    <Reference Include="Microsoft.CSharp" />
</ItemGroup>  
  • If you do not specify a condition, it matches with the first and default framework in the <TargetFrameworks> element which is .netcoreapp1.1. E.g.
<ItemGroup>  
    <PackageReference Include="Newtonsoft.Json" Version="10.0.2" />
  </ItemGroup>
  • To build for a particular framework we use the following command in the cli:
dotnet build -f <frameworkName>  

E.g.

dotnet build -f net46  

Or

dotnet build -f net452  

If this helped you, it'd be nice to know. Also if you had any issues with doing this, please let us know in the comments section.

Happy Coding! 😋

Show Comments