Mark a whole assembly as dynamically accessed when Application Trimming

Viewed 393

With .NET 5, we can trim our project to reduce its footprint. If we know that we will access a Type via reflection, we can mark it as dynamically accessed:

public void DoSomethingReflective<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T>();

But is there also a way to mark a whole assembly as dynamically accessed?

public void DoSomethingReflective(Assembly assembly);
1 Answers

Application Trimming has been expanded in .Net 5 and gives you finer grained control over what can be an implicitly dangerous process.

Although the attributes are targeted (and handy), at this stage they lack support for more complex scenarios. Though, my gut feeling is this feature set will expand going forward. However, you can of now use a XML based configuration files which have a wide range of complex options and use cases in mind.

Basically, they break down to the following

  • Preservation
  • External Attribution
  • Feature switches

In regards to perseveration (which is what you want), you would add the TrimmerRootDescriptor tag to the project file

<ItemGroup>
   <TrimmerRootDescriptor Include="Whatever.xml" />
</ItemGroup>

Then in the configuration file, it's just a matter of setting the linker to the assembly via the FullName tag

<linker>
  <assembly fullname="SomeAssembly" preserve="all" />
</linker>

or a fully qualified name

<linker>
  <assembly fullname="SomeAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null">
</linker>

If there are types under an assembly tag, only the listed types and members will be flagged for preservation unless preserve=all is specified at the assembly level.

<assembly fullname="AssemblyA">
   <type fullname="AssemblyA.One" preserve="all" />
   <type fullname="AssemblyA.Two" />

Inversely, if the type doesn’t have a preserve attribute and it doesn’t list any children then all of its members will be flagged for preservation.


Additional Resources

Customizing Trimming in .NET 5

Preservation

The trimmer will automatically include all code that it thinks can be reached by the application. The preservation scenario for using XML files is to tell the trimmer to “preserve” code and not to remove it, even if it doesn’t think it is used. This is great for code that is discovered and invoked by reflection.

...

When an assembly, type or member are listed in the xml, the default action is preservation, which means that regardless of whether the trimmer thinks they are used or not, they will be preserved in the output. Preservation is additive, it will tell the trimmer what extra code that it doesn’t think is needed should be kept, if it thinks a type or member is needed then it will include it, even if it would not be included based on the preservation tags.

Related