How to Resolve Trimming Errors in .NET 6 When Using `<PublishTrimmed>` with a Referenced Project?

164 views Asked by At

I'm working on a .NET 6 application and trying to reduce the executable size using <PublishTrimmed>. I followed the guidelines from Microsoft's documentation on Preparing Libraries for Trimming, but I'm facing trimming errors.

Here's the .csproj file of my root application:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>

    <PublishTrimmed>true</PublishTrimmed> <!-- Needs to be set here, if multitargeted -->
  </PropertyGroup>
  
  <ItemGroup>
    <ProjectReference Include="..\NonTrimmableLib\NonTrimmableLib.csproj" />
  </ItemGroup>
</Project>

And the .csproj file of the referenced project (NonTrimmableLib.csproj):

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>

    <IsTrimmable>false</IsTrimmable> <!-- doesn't work -->
    <EnableTrimAnalyzer>true</EnableTrimAnalyzer> <!-- doesn't work -->
  </PropertyGroup>
</Project>

I run the following command from the command line:

dotnet publish .\RootApp.csproj -r linux-x64 --self-contained -p:PublishSingleFile=true

but I get warning / errors about incompatible code:

  NonTrimmableLib -> C:\Users\user\source\repos\TrimmingTest\NonTrimmableLib\bin\Debug\net6.0\NonTrimmableLib.dll
  RootApp -> C:\Users\user\source\repos\TrimmingTest\RootApp\bin\Debug\net6.0\linux-x64\RootApp.dll
  Optimizing assemblies for size. This process might take a while.
  
C:\Users\user\source\repos\TrimmingTest\NonTrimmableLib\Class1.cs(11,13): Trim analysis warning IL2026: NonTrimmableLib.Serializer.SerializeType(Type, Object):
 Using member 'System.Xml.Serialization.XmlSerializer.XmlSerializer(Type)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code.
 Members from serialized types may be trimmed if not referenced directly. [C:\Users\user\source\repos\TrimmingTest\RootApp\RootApp.csproj]
 
C:\Users\user\source\repos\TrimmingTest\NonTrimmableLib\Class1.cs(15,13): Trim analysis warning IL2026: NonTrimmableLib.Serializer.SerializeType(Type, Object):
 Using member 'System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter, Object)' which has 'RequiresUnreferencedCodeAttribute' can break functionality when trimming application code. 
 Members from serialized types may be trimmed if not referenced directly. [C:\Users\user\source\repos\TrimmingTest\RootApp\RootApp.csproj]

Ideally the goal would be to trim only contents of .NET runtime and do not touch my referenced code or referenced NuGet assemblies.

0

There are 0 answers