AOT with Reflection #95244
-
Scenerio: In most of my use-cases the types are known at build-time, and I don't expect any users to be loading types with APIs such as Questions: And if that is the case, is disabling those warning wise? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
I've been working for the last few weeks on making our codebase work with Native AOT and had to deal with reflection issues. Key problem is that data gets trimmed, to deal with some of those cases I had to do the following bit in code:
Also, you can use the following in project file in order to prevent trimmer from cutting too much - Relection seems to work as long as types were not trimmed away. |
Beta Was this translation helpful? Give feedback.
-
It's actually not true that generic parameters are always known at compile time. Code can call for example For this (and other reasons) the tooling requires you to annotate the types (either generic parameters, or For example: IEnumerable<string> GetPropertyNames<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T>()
{
return typeof(T).GetProperties().Select(p => p.Name);
} More details are described here: https://learn.microsoft.com/en-us/dotnet/core/deploying/trimming/prepare-libraries-for-trimming?pivots=dotnet-8-0#dynamicallyaccessedmembers. The samples in that article are about The warnings produced by the tools will let you know what requirements (
Disabling these warnings is absolutely not recommended. In lot of cases the tooling is not clever enough to figure it out without the annotations mentioned above and the code could fail at runtime. As mentioned here: https://learn.microsoft.com/en-us/dotnet/core/deploying/trimming/prepare-libraries-for-trimming?pivots=dotnet-8-0#unconditionalsuppressmessage, suppressing warnings should be only considered as the last resort and you need to be very careful about it. (Trust me, we got it wrong ourselves so many times, that now we're basically trying to avoid it at any cost). |
Beta Was this translation helpful? Give feedback.
It's actually not true that generic parameters are always known at compile time. Code can call for example
typeof(List<>).MakeGenericType(Console.ReadLine())
in which case the generic parameter is not known statically. But also, early on we decided against doing automatic propagation of types across method boundaries because if there are problems which would need to be reported to the user, the experience around it can be really bad (if you ever worked with templates in C++, you are probably familiar with the really complex errors you can get from the compiler, this would be similar and some cases even worse).For this (and other reasons) the tooling requires you to annotate the types (ei…