DEV Community

jsakamoto
jsakamoto

Posted on

How to get rid of unused .dll from loading contents on Blazor WebAssembly apps

Backgrounds

Imagine a scenario in which a class library project is referenced from a Blazor WebAssembly app project.

The structure of the sample project

And in this scenario, all types exposed from the class library are never used in the Blazor app on its release build for some reason.
(It might be controlled by conditional compile, one of the C# compiler's features.)

In this case, maybe we expect the class library .dll files never loaded on the published Blazor app with "Release" configuration by trimming the feature of the "IL Linker".

However, unexpectedly, the class library .dll file is loaded into the browser even though it is never used anywhere. 😱
The

Solution

The solution to avoid loading unused class library .dll files is to add the AssemblyMetadata("IsTrimmable", "True") attribute to the class library code as an assembly level.

// This code should be added somewhere .cs files in the class library.
[assembly: System.Reflection.AssemblyMetadata("IsTrimmable", "True")]
Enter fullscreen mode Exit fullscreen mode

After doing that, the browser will never load the class library .dll file if the class library is not used anywhere. 🎉
The

for .NET 5

Unfortunately, the AssemblyMetadata("IsTrimmable", "True") attribute has no effect at all on .NET 5 platform.

The solution on .NET 5 platform for this scenario is to append some of the MSBuild scripts inside the Blazor WebAssembly app's project file, like this.

<!-- This is a .csproj file of a Blazor WebAssembly app, not a class library.  -->
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
  ...
  <Target Name="_ConfigureAssemblyLevelTrimming" BeforeTargets="PrepareForILLink">
    <ItemGroup>
      <ManagedAssemblyToLink Condition="'%(Filename)' == 'SampleLib'">
        <IsTrimmable>true</IsTrimmable>
      </ManagedAssemblyToLink>
    </ItemGroup>
  </Target>
  ...
Enter fullscreen mode Exit fullscreen mode

If the class library is going to be packed as a NuGet package, that MSBuild script like above should also be included in the NuGet package file and be configured to be imported automatically into a project that references the package.

This is not an easy way than platforms of .NET 6 or later, but there is no way on .NET 5 platform.

And remember, the end of support of the .NET 5 will be May 8, 2022.

Official documents

For more details, please see also Microsoft's official documents site as below link.

📄 "Trim additional assemblies | Microsoft Docs"

The official document explains about <TrimmableAssembly/> MSBuild items too.
But in this article, I don't mention it because the <TrimmableAssembly/> MSBuild items are not so important, in my opinion.

Top comments (0)