Reflection is very cool, the meta data system of .Net is pretty cool. You can create objects of a given class, without knowing it at compile time, by just looking it up and instantiating it using reflection. But how can I look up a type? Some times you only know the name of a type you want to create, without knowing the correct assembly. Let’s say we have an assembly, that holds a service implementation to create a object:
class MyService { object GetObject(string typeName) { } }
The class we want to create, is in the assembly from where that function gets called. That is ok, but we don’t know that assembly at compile time, we can only find it out, when the function gets called. But how?
The regular solution would be, to use System.Reflection.Assembly.GetCallingAssembly(). But when we do this in .Net Nativ, we get an exception at runtime:
Unhandled exception at 0x78A7B264 (Windows.UI.Xaml.dll) in BlankApp3.UWP.exe: 0xC000027B
I think this is a bug within the .Net native compiler. But how can we find a workaround for that problem?
1. using a fully qualified type name
object GetObject(string typeName) { var type = Type.GetType(typeName); return Activator.CreateInstance(type); }
You can then actually use the complete name, including the namespace, when calling the function. (Something like: GetObject(“BlankApp3.Views.MainPage”)), so it’s not possible to lookup a type by name. But for our use case, it is enough.
2. lookup the assembly by name
object GetObject(string assemblyName, string typeName) { var assemblies = AppDomain.CurrentDomain.GetAssemblies(); var assembly = assemblies.FirstOrDefault(asm => asm.GetName().Name.Equals(assemblyName)); var type = assembly.GetTypes().FirstOrDefault(t => t.Name.Equals(typeName)); return Activator.CreateInstance(type); }
This is the most flexible solution in our case (but it takes more time). You can even look through all loaded assemblies, and find types by name. Please be aware that there is another bug, preventing you from getting all types from all loaded assemblies (the solution can be found on stackoverflow).
You’re answer on StackOverflow was spot on for the .Net Native/Reflection stuff. The reflection works beautifully now, no arcane error messages. 😀