在应用程序修整时将整个程序集标记为动态访问

Mark a whole assembly as dynamically accessed when Application Trimming

使用 .NET 5,我们可以 trim 我们的项目减少它的足迹。如果我们知道我们将通过反射访问一个Type,我们可以将其标记为动态访问:

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

但是是否还有一种方法可以将整个程序集标记为动态访问?

public void DoSomethingReflective(Assembly assembly);

Application Trimming 已在 .Net 5 中得到扩展,让您可以更精细地控制隐含危险的过程。

虽然 属性 是有针对性的(并且方便),但在现阶段它们缺乏对更复杂场景的支持。不过,我的直觉是这个功能集会在未来扩展。但是,您现在可以使用基于 XML 的配置文件,其中考虑了广泛的复杂选项和用例。

基本上,它们分解为以下

  • 保存
  • 外部归因
  • 功能开关

关于坚持(这就是你想要的),你可以将 TrimmerRootDescriptor 标签添加到项目文件

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

然后在配置文件中,只需通过 FullName 标签

linker 设置为 assembly
<linker>
  <assembly fullname="SomeAssembly" preserve="all" />
</linker>

或完全限定名称

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

如果程序集标记下有类型,只有列出的类型和成员将被标记为保留,除非在程序集级别指定 preserve=all

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

相反,如果该类型没有保留属性并且它没有列出任何子项,那么它的所有成员都将被标记为保留。


其他资源

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.