Technology advances at great speed. As technologies advance, we must ensure that we keep up with those advancements. If we do not we face losing support or worse by having unlatched security holes within our code base. In December, Microsoft announced a new .NET core long term support version - .net core 3.1. how do we as developers ensure we can easily transition from 2.2 to 3.1 especially within nuget packages that support both frameworks?

Within the project file we can actually target multiple frameworks. In order to do this we c must setup the project file correctly:

<TargetFrameworks>.netcoreapp2.2;.netcoreapp3.1</TargetFrameworks>

Notice the tag is plural whereas the typical Framework tag is singular. But we have another issue. What do we do about nuget packages that only support one framework or the other? Here is where conditionals come into place. We can programmatically pull in different versions based on several different parameters. For this we will set up a condition to match on the framework that we are building it for. We will then use the microsoft.extensions.logging package for the specific framework we are working with for a quick example.

<ItemGroup condition="'$(TargetFramework)' == '.netcoreapp2.2'")
  <PackageReference Include="Microsoft.Extensions.Logging" Version="2.2.0" />
</ItemGroup>

<ItemGroup condition="'$(TargetFramework)' == '.netcoreapp3.1'")
  <PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.0" />
</ItemGroup>

It becomes tricky when we must start using preprocessor directives for alternative code execution. While we would like to override this at all costs - it’s simply not an option for certain cases such as breaking changes. I would recommend refactoring these as it creates messy code and messy code is usually unmanageable in the long run.

Here’s a quick example of using a preprocessor directive based on your current framework:

#if NETCOREAPP2_2
//Do 2.2 specific work
#endif

#if NETCOREAPP3_1
//Do 3.1 specific work
#endif

Now make sure you have both frameworks on your build server and you’ll be good to go! As usual reach out to me on LinkedIn or Twitter with questions or comments!

Tom