Search code examples
c#.netreflectionaotnative-aot

C# .net core native AOT with reflection Activator.CreateInstance


I am trying to use reflection's Activator.CreateInstance method to generate the required module with parameters like below.

 public TModule CreateModule<TModule>(params object[]? parameters) where TModule : ApplicationModule
    {
        /*
         * Create module
         */
        TModule? module = Activator.CreateInstance(typeof(TModule), parameters) as TModule;
        if (module is null)
            throw new Exception($"Failed to create module with type: {typeof(TModule).Name}");

        /*
         * Register it to the pending modules
         */
        _pendingModules.Add(module);

        return module;
    }

But it always return

  Unhandled Exception: System.MissingMethodException: No parameterless constructor defined for type 'Runtime.Reflection.ReflectionModule'.
   at System.ActivatorImplementation.CreateInstance(Type, Boolean) + 0x121
   at Runtime.Application.Application.CreateModule[TModule]() + 0x35
   at EditorPlayer.Program.Main(String[]) + 0x107
   at EditorPlayer!<BaseAddress>+0x862f1b

Even though the target class has default constructor it still throws the same error. I thought reflection was present in native AOT builds.


Solution

  • It seems compiler sometimes may fail to detect the reflection types used in a codebase. In such cases as these one should create and import an rd.xml file into project settings(rd stands for runtime directives). Here in this xml file you can specify the types in a specific assembly to be consumed or you can specify types directly so that can be included in the native aot build.

    For generics types it seems that adding new() end of the generic method helps compiler to mark the generic type and to be exported in to the native aot build.

    Here's some links that may help with the native aot reflection.

    https://github.com/dotnet/corert/blob/master/Documentation/using-corert/reflection-in-aot-mode.md

    https://github.com/dotnet/corert/blob/master/Documentation/using-corert/rd-xml-format.md