How to trim dependencies in a .NET MAUI Android app?

I have an .NET MAUI Android app in .Net 7 which uses PdfSharpCore and MigraDocCore to generate reports as PDF files. Everything works fine when I build and deploy the app on Debug configuration.

However, if I build and deploy it on Release, no matter what is changed, clicking the button to render a PDF file always throws the exact same exception:

System.NullReferenceException: Object reference not set to an instance of an object at MigraDocCore.DocumentObjectModel.Internals.ValueDescriptor.CreateValue() at MigraDocCore.DocumentObjectModel.Internals.DocumentObjectDescriptor.GetValue(DocumentObject, GV) at MigraDocCore.DocumentObjectModel.Internals.Meta.GetValue(DocumentObject, String, GV) at MigraDocCore.DocumentObjectModel.DocumentObject.GetValue(String, GV) at MigraDocCore.DocumentObjectModel.Visitors.MergedCellList.GetEffectiveBorders(Cell) at MigraDocCore.Rendering.TableRenderer.FormatCells() at MigraDocCore.Rendering.TableRenderer.InitFormat(Area, FormtInfo) at MigraDocCore.Rendering.TableRenderer.Format(Area, FormtInfo) at MigraDocCore.Rendering.TopDownFormatter.FormatOnAreas(XGraphics, Boolean) at MigraDocCore.Rendering.FormattedDocument.Format(XGraphics) at MigraDocCore.Rendering.DocumentRenderer.PrepareDocument() at MigraDocCore.Rendering.PdfDocumentRenderer.PrepareDocumentRender(Boolean) at MigraDocCore.Rendering.PdfDocumentRenderer.PrepareRenderPages(Boolean) at MigraDocCore.Rendering.PdfDocumentRenderer.RenderDocument() at FarmOrganizer.IO.Exporting.PDF.PdfBuilder.Build() at FarmOrganizer.ViewModels.ReportPageViewModel.ExportReportAsPDF()

I know it looks like an issue with MigraDocCore itself, but if I disable AOT and trimming for Release, PDF exporting works exactly as expected. However, at the same time I don’t want to completely abandon optimization benefits that come from AOT and trimming (which are noticeable in my app).

So here’s my question – how do I properly set up trimming so that it trimms everything BUT MigraDocCore, PdfSharpCore and all their dependencies?

Exploring the internet yielded no working results. I tried adding the following:

<TrimmerRootAssembly Include="MigraDocCore.Rendering" />

But with this added in my .csproj file, it breaks the project entirely with VisualStudio stating that “the element in Include was not recognized”. I tried adding the “.ddl” suffix didn’t work. If I add the TrimmerRootAssembly like this:

<TrimmerRootAssembly>MigraDocCore.Rendering</TrimmerRootAssembly>

It’s completely ignored.

Is it even possible to trim dependencies or did I not get the definition of an assembly right?

Leave a Comment