One of the significant differences between .NET Core and .NET Framework is that .NET Core promotes self-contained deployment, i.e., everything required to run to bundle the application together. It doesn’t rely on having the framework installed separately. The drawback is the size; it pulls along a complete copy of the runtime & framework.
To resolve the size problem, Microsoft has introduced an alternative to cut unused assemblies as part of publishing self-contained applications known as “assembly linker.”
Optionally during the publishing process, a trim phase occurs, which does a walkthrough of the code classes identifying the assemblies that are used. It will then only package required assemblies into the app, thereby reducing the size of the application.
In .NET 5, open the assemblies, and removing the types and members that are not used by the application, further reducing the size.
For example, for a basic dot net core hello world application, the size of assemblies are:
To perform trimming at assembly-level, use the dot net publish command either without a trim mode, or use CopyUsed in the project file:
<Project Sdk=”Microsoft.NET.Sdk”> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <RuntimeIdentifier>win10-x64</RuntimeIdentifier> <PublishTrimmed>true</PublishTrimmed <TrimMode>CopyUsed</TrimMode> </PropertyGroup> </Project>
Or on the command line:
dotnet publish -r win10-x64 -p:PublishTrimmed=True [-p:TrimMode=CopyUsed]
.NET 5 trimming take it further deep into the code and remove types and members that are not used. It can have a significant effect where only a small subset of an assembly is used.
Further reduction in the size of application can be made by enabling Member-level trimming by putting TrimMode=Link in the project file
<Project Sdk=”Microsoft.NET.Sdk”> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <RuntimeIdentifier>linux-x64</RuntimeIdentifier> <PublishTrimmed>true</PublishTrimmed <TrimMode>Link</TrimMode> </PropertyGroup> </Project>
Or using the command line
dotnet publish -r win10-x64 -p:PublishTrimmed=True -p:TrimMode=Link
Member-level trimming has more risk than assembly-level trimming, and so is being released as an experimental feature.
With assembly-level trimming, it’s more apparent when a required assembly is missing.
With member level trimming, you need to have exhaustive testing of the app to ensure that nothing has been trimmed that could be required.
Thank you for reading. Keep visiting and share this in your network. Please put your thoughts and feedback in the comments section.
Follow me on Medium