Trimming/AOT : is it possible to propagate DynamicDependency to all children of a base class? #102972
-
I use the following code to record some debugging information from exceptions thrown in my program. I use reflection to extract data from exception properties. Unfortunately, this mechanism no longer works if the program is trimmed. I've tried to use the Is there any other way of making the Thanks! internal class Program
{
public static void Main()
{
ExceptionData? data = null;
try
{
throw new ArgumentException("Fake message", "fakeParam");
}
catch (Exception ex)
{
data = new ExceptionData(ex);
}
if (data.Data!.TryGetValue(nameof(ArgumentException.ParamName), out string? value) && value == "fakeParam")
Console.WriteLine("ok"); // if not trimmed
else
Console.WriteLine("not ok"); // if trimmed because the ArgumentException.ParamName property is not kept by the trimmer
}
}
public class ExceptionData
{
public Dictionary<string, string?>? Data { get; }
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicProperties, typeof(Exception))]
// TODO : how to tell the trimmer to keep all properties of all classes that inherit from the Exception base class (and not only the Exception class)
public ExceptionData(Exception exception)
{
Type type = exception.GetType();
PropertyInfo[] properties = type.GetProperties(); // warning IL2075 from the linker
var data = new Dictionary<string, string?>(properties.Length);
foreach (PropertyInfo property in properties)
{
object? value = property.GetValue(exception);
if (value != null)
data.Add(property.Name, value.ToString());
}
Data = data;
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
There is no mechanism to do this, sorry. This pattern is not compatible with trimming. The main reason there are no facilities for this is that it would be too easy to end up with code that completely prevents trimming - e.g. replace |
Beta Was this translation helpful? Give feedback.
Your scenario is similar to the "reflection based serialization" bucket that we keep thinking about, but don't have anything that works with static analysis right now.