Saturday, 26 February 2022

Multi Target Framework for .NET Core Application

It is possible to target multiple framework for .NET Core application. But it have some limitations. For example, if the project target netcoreapp3.1 and net6.0, features that are available on net6.0 will not longer be supported. Due to this, it is rarely to do so unless you got hit with situation where you want to upgrade to newest .NET version but due to certain servers yet to installed the latest .NET core runtime.

First and foremost, make sure you have the targeted framework installed. Otherwise you get hit with an error while compiling your code. For example, if you are targeting netcoreapp3.1 and net6.0, make sure both of them is installed on your machine.

To get started, open up your project by double clicking on it and look for TargetFramework. Rename it to TargetFrameworks and specify net6.0;netcoreapp3.1

<TargetFrameworks>net6.0;netcoreapp3.1</TargetFrameworks>

Next item to look out for is the NuGet packages. You can specify different NuGet package version to be installed for different framework. As an example, I only have 1 NuGet package, which is Swashbuckle.AspNetCore as shown below. 

<ItemGroup>
  <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>

You are required to remove it and then create 2 separate ItemGroup as shown below. By doing so, Swashbuckle.AspNetCore version 6.2.3 will be installed for net6.0, whereas version 5.6.3 will be installed for netcoreapp3.1

<ItemGroup Condition="$(TargetFramework)=='net6.0'">
  <PackageReference Include="Swashbuckle.AspNetCore">
    <Version>6.2.3</Version>
  </PackageReference>
</ItemGroup>
<ItemGroup Condition="$(TargetFramework)=='netcoreapp3.1'">
  <PackageReference Include="Swashbuckle.AspNetCore">
    <Version>5.6.3</Version>
  </PackageReference>
</ItemGroup>

Once you saved your changes, you may notice the Background Task which locate at the bottom left of your visual studio is in progress of grabbing the NuGet packages for your project. Make sure to wait it to complete before compiling your code. Also, you will be able to see 2 different dependencies in your project under the Solution Explorer.

Multiple dependencies





No comments:

Post a Comment