Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamic Type Creation with a Constructor that reference its dependencies
    text
    copied!<p>I have the following classes:</p> <pre><code>public class Entity&lt;T&gt; where T : Entity&lt;T&gt; { public Factory&lt;T&gt; Factory { get; private set; } public Entity(Factory&lt;T&gt; factory) { Factory = factory; } } public class Factory&lt;T&gt; { } public class MyEntity : Entity&lt;MyEntity&gt; { public MyEntity(Factory&lt;MyEntity&gt; factory) : base(factory) { } } </code></pre> <p>I am trying to dynamically create class MyEntity with the constructor specified. So far I have the following code:</p> <pre><code>class Program { static ModuleBuilder _moduleBuilder; public static ModuleBuilder ModuleBuilder { get { if (_moduleBuilder == null) { AssemblyBuilder asmBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(new AssemblyName("Dynamic"), AssemblyBuilderAccess.Run); _moduleBuilder = asmBuilder.DefineDynamicModule("MainModule"); } return _moduleBuilder; } } static void Main(string[] args) { TypeBuilder typeBuilder = ModuleBuilder.DefineType("MyEntity", TypeAttributes.Public); Type baseType = typeof(Entity&lt;&gt;).MakeGenericType(typeBuilder); typeBuilder.SetParent(baseType); Type factoryType = typeof(Factory&lt;&gt;).MakeGenericType(typeBuilder); ConstructorBuilder cBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { factoryType }); ILGenerator ctorIL = cBuilder.GetILGenerator(); ctorIL.Emit(OpCodes.Ldarg_0); ctorIL.Emit(OpCodes.Ldarg_1); ConstructorInfo c = baseType.GetConstructor(new Type[] { factoryType }); ctorIL.Emit(OpCodes.Call, c); ctorIL.Emit(OpCodes.Ret); Type syType = typeBuilder.CreateType(); Console.ReadLine(); } } </code></pre> <p>The code failed @ <code>ConstructorInfo c = baseType.GetConstructor(new Type[] { factoryType })</code>. I got a NotSupportedException.</p> <p>Is there any way to achieve this? I have been stonewalled by this for three days. Any help would be appreciated.</p> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload