Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activator.CreateInstance(type) Throws Exception

Actually it is very strange exception, because it happens only when I build the project as Release and does not happen at all when I choose Debug. In debug mode, the app works perfect and the following code works well.

Here is the code of my extension method:

public static T DeepClone<T>(this T source) where T : UIElement
{
   T result;

   // Get the type
   Type type = source.GetType();

   // Create an instance
   result = Activator.CreateInstance(type) as T; //throws exception here only if I build project as (release)

   CopyProperties<T>(source, result, type);
   DeepCopyChildren<T>(source, result);

   return result;
}

The exception is:

An exception of type 'System.MissingMethodException' occurred in System.Private.Reflection.Execution.dll but was not handled in user code

Additional information: MissingConstructor_Name, Windows.UI.Xaml.Controls.RelativePanel. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485

I've found some related questions to this exception, but they all are pointing to missing libraries or update libraries like this but didn't change anything in my app.

like image 921
Moamen Naanou Avatar asked Mar 09 '23 21:03

Moamen Naanou


1 Answers

This problem is related to the fact that Release build of UWP apps uses the .NET native toolchain. In this mode reflection needs some hints to work properly. Aparently the constructor of the RelativePanel is not available for reflection.

Luckily there is a workaround for this as described in this blogpost.

In your UWP project's Properties folder is a file called default.rd.xml. Open it and add the following line inside the <Applications> element:

<Type Name="Windows.UI.Xaml.Controls.RelativePanel" 
      Dynamic="Required All" Activate="Required All" /> 

The Dynamic attribute should ensure reflection is possible and the Activate attribute should ensure the constructors are available for activation - which is key for your case.

This should include all members of RelativePanel for reflection and everything should work as expected.

You can see more details on the default.rd.xml file structure here.

like image 50
Martin Zikmund Avatar answered Mar 21 '23 10:03

Martin Zikmund