Home > Software design >  Prevent Method from being Trimmed
Prevent Method from being Trimmed

Time:02-26

I'm trying to prevent IL Linker from trimming a method in my .NET WebAssembly. Because the method Callback() is called externally, the static analysis believes it is not used and removes it. There's a few attributes I've tried, DynamicDependency, DynamicallyAccessedMembers, and RequiresUnreferencedCode, but I have a feeling I'm not using them correctly.

I'm aware I can prevent trimming with XML config or by doing something like if(someAlwaysFalseCondition) { Callback(); } but those aren't feasible solutions in my context.

How should I apply an attribute to Callback() to prevent it from being trimmed by the IL Linker?

public class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Loaded.");
    }
    
    public static void Callback()
    {
        Console.WriteLine("Callback");
    }
}

CodePudding user response:

The attribute is applied to methods, and specifies which other types, methods or members should be included. In this example its "Main()":

public class Program
{
    [DynamicDependency(DynamicallyAccessedMemberTypes.All, typeof(Program))]
    static void Main(string[] args)
    {
        Console.WriteLine("Loaded.");
    }

    public static void Callback()
    {
        Console.WriteLine("Callback");
    }
}
  • Related