9c2d3-image-4

Creating a cross platform package – Part 2

Introduction

In theCreating a cross platform package - Part 1, I covered the steps required to migrate your project to the new format. In this post, I will move on to the next stage and cover how to adapt the solution to target multiple frameworks.

Project Changes

The first step is to modify the project and specify which frameworks you want to target. This is a simple change; modify the <TargetFramework> element to be <TargetFrameworks> and then specify the frameworks you wish to target.

1<TargetFrameworks>net471;net5.0;net6.0</TargetFrameworks>

After the project has been modified, you will also need to update the package references, ensuring they target the correct framework. This is straightforward; add a condition to the parent <ItemGroup>.

1<ItemGroup Condition="'$(TargetFramework)' == 'net5.0'">
2    <PackageReference Include="EPiServer.CMS.UI.Core" Version="[12.0.3,13)" />
3    <PackageReference Include="EPiServer.Framework.AspNetCore" Version="[12.0.3,13)" /> 
4    <PackageReference Include="EPiServer.Framework" Version="[12.0.3,13)" />
5	
6    <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.0" />
7    <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.0" />
8    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0" />
9</ItemGroup>

There may also be other sections of your project file that will require you to use these condition clauses.

Code Changes

After changing the project to target multiple frameworks, you will get compilation errors; you will need to fix these by creating different implementations of your code and wrapping each implementation with a preprocessor statement to indicate which framework the code is targeting.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives

1#if NET461
2 // Code specific for .net framework 4.6.1
3#elif NET5_0
4 // Code specific for .net 5.0
5#elif NET5_0_OR_GREATER
6 // Code specific for .net 5.0 (or greater)
7#else
8 // Code for anything else
9#endif

You may need to alter a couple of lines within a class, or in some cases, you will need to deliver a completely different approach. A good example would be Middleware replacing a .NET Framework HTTPModule.

Wrapping it all up

Everyone's journey while converting their module will differ. The type of module, whether it has a UI, etc, will determine the complexity.

Whilst you are modifying the code base, I would strongly recommend :

  1. Keep the 'DRY' principle and refactor your code when necessary so that you are not repeating sections of code.

  2. If you have an interface that uses WebForms then it is probably better to replace this with an interface that works for all the different frameworks rather than trying to maintain two different interfaces.