Search code examples
c#.net-standard-2.0

Target .NET 4.x and .NET Standard 2.0


Last year I added .NET Standard 2.0 support to the Network library. I did achieve this by creating a second (.NET Standard) project, and basically copy + paste the sourcecode. With some adjustments it was ready to go.

But since I add features on demand, it is really bothersome to change the same thing in both projects. It would be great to just create one code-base and simply change the compile target.

Pre-Compile statements aren't an option, because the .NET 4.x version does additionally include some NuGet packages, which aren't available for .NET Standard.

The solution I can currently think of is, to create a shared library, including all the cross-project classes. Or is there a much smoother solution?


Solution

  • Solved the Problem with the suggested solution. The .csproj Looks like following

    <Project Sdk="Microsoft.NET.Sdk">  
      <PropertyGroup>
        <TargetFrameworks>net46;netstandard2.0</TargetFrameworks>
      </PropertyGroup>
      <PropertyGroup>
         <RestoreProjectStyle>PackageReference</RestoreProjectStyle>
      </PropertyGroup>
      <ItemGroup>
        <Compile Remove="packages\**" />
        <EmbeddedResource Remove="packages\**" />
        <None Remove="packages\**" />
      </ItemGroup>
    
      <ItemGroup>
        <!-- PackageReferences for all TargetFrameworks -->
      </ItemGroup>
    
      <ItemGroup Condition="'$(TargetFramework)' == 'net46' ">
        <!-- PackageReferences for net46 TargetFramework -->
      </ItemGroup>
    
      <ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0' ">
        <!-- PackageReferences for standard2.0 TargetFramework -->
      </ItemGroup>
    </Project>
    

    The only issue currently: I can't use the NuGet Package-Manager. I have to add every entry manually into the correct ItemGroup.

    EDIT: The manual edit is only required if the packages are not supported by both TargetFrameworks. Simply Change in the Settings -> NuGet-Paket-Manager -> Default Format -> PackageReference

    enter image description here